root/src/xdisp.c

/* [<][>][^][v][top][bottom][index][help] */

DEFINITIONS

This source file includes following definitions.
  1. it_char_has_category
  2. char_can_wrap_before
  3. char_can_wrap_after
  4. fill_column_indicator_column
  5. redisplay_other_windows
  6. wset_redisplay
  7. fset_redisplay
  8. bset_redisplay
  9. bset_update_mode_line
  10. wset_update_mode_line
  11. ATTRIBUTE_FORMAT_PRINTF
  12. ATTRIBUTE_FORMAT_PRINTF
  13. window_text_bottom_y
  14. window_box_width
  15. window_box_height
  16. window_box_left_offset
  17. window_box_right_offset
  18. window_box_left
  19. window_box_right
  20. window_box
  21. window_box_edges
  22. line_bottom_y
  23. DEFUN
  24. default_line_pixel_height
  25. string_from_display_spec
  26. window_hscroll_limited
  27. reset_box_start_end_flags
  28. pos_visible_p
  29. check_char_and_length
  30. string_pos_nchars_ahead
  31. string_pos
  32. c_string_pos
  33. number_of_chars
  34. compute_string_pos
  35. estimate_mode_line_height
  36. pixel_to_glyph_coords
  37. x_y_to_hpos_vpos
  38. frame_to_window_pixel_xy
  39. get_glyph_string_clip_rects
  40. get_glyph_string_clip_rect
  41. get_phys_cursor_geometry
  42. remember_mouse_glyph
  43. adjust_window_ends
  44. hscrolling_current_line_p
  45. safe_eval_handler
  46. safe__call
  47. safe_call
  48. safe_call1
  49. safe__call1
  50. safe_eval
  51. safe__eval
  52. safe_call2
  53. CHECK_IT
  54. CHECK_WINDOW_END
  55. init_iterator
  56. get_narrowed_width
  57. get_narrowed_len
  58. get_medium_narrowing_begv
  59. get_medium_narrowing_zv
  60. get_nearby_bol_pos
  61. get_small_narrowing_begv
  62. get_large_narrowing_begv
  63. get_large_narrowing_zv
  64. unwind_narrowed_begv
  65. start_display
  66. in_ellipses_for_invisible_text_p
  67. init_from_display_pos
  68. init_to_row_start
  69. init_to_row_end
  70. handle_stop
  71. compute_stop_pos
  72. compute_display_string_pos
  73. compute_display_string_end
  74. handle_fontified_prop
  75. face_at_pos
  76. handle_face_prop
  77. underlying_face_id
  78. face_before_or_after_it_pos
  79. handle_invisible_prop
  80. setup_for_ellipsis
  81. find_display_property
  82. get_display_property
  83. display_min_width
  84. handle_display_prop
  85. handle_display_spec
  86. display_prop_end
  87. handle_single_display_spec
  88. display_prop_intangible_p
  89. single_display_spec_string_p
  90. display_prop_string_p
  91. string_buffer_position_lim
  92. string_buffer_position
  93. handle_composition_prop
  94. handle_overlay_change
  95. next_overlay_string
  96. compare_overlay_entries
  97. load_overlay_strings
  98. get_overlay_strings_1
  99. get_overlay_strings
  100. push_it
  101. iterate_out_of_display_property
  102. restore_face_box_flags
  103. pop_it
  104. back_to_previous_line_start
  105. strings_with_newlines
  106. forward_to_next_line_start
  107. back_to_previous_visible_line_start
  108. reseat_at_previous_visible_line_start
  109. reseat_at_next_visible_line_start
  110. reseat
  111. reseat_1
  112. reseat_to_string
  113. lookup_glyphless_char_display
  114. merge_escape_glyph_face
  115. merge_glyphless_glyph_face
  116. forget_escape_and_glyphless_faces
  117. get_next_display_element
  118. set_iterator_to_next
  119. next_element_from_display_vector
  120. get_visually_first_element
  121. next_element_from_string
  122. next_element_from_c_string
  123. next_element_from_ellipsis
  124. next_element_from_image
  125. next_element_from_xwidget
  126. next_element_from_stretch
  127. compute_stop_pos_backwards
  128. handle_stop_backwards
  129. next_element_from_buffer
  130. next_element_from_composition
  131. move_it_in_display_line_to
  132. move_it_in_display_line
  133. move_it_to
  134. move_it_vertically_backward
  135. move_it_vertically
  136. move_it_past_eol
  137. move_it_by_lines
  138. partial_line_height
  139. fast_move_it_horizontally
  140. in_display_vector_p
  141. window_text_pixel_size
  142. DEFUN
  143. format_nargs
  144. add_to_log
  145. vadd_to_log
  146. message_log_maybe_newline
  147. message_dolog
  148. message_log_check_duplicate
  149. message3
  150. message_to_stderr
  151. message3_nolog
  152. message1
  153. message1_nolog
  154. message_with_string
  155. ATTRIBUTE_FORMAT_PRINTF
  156. message
  157. update_echo_area
  158. ensure_echo_area_buffers
  159. with_echo_area_buffer
  160. with_echo_area_buffer_unwind_data
  161. unwind_with_echo_area_buffer
  162. setup_echo_area_for_printing
  163. display_echo_area
  164. display_echo_area_1
  165. resize_echo_area_exactly
  166. resize_mini_window_1
  167. resize_mini_window
  168. current_message
  169. current_message_1
  170. push_message
  171. restore_message
  172. pop_message_unwind
  173. check_message_stack
  174. clear_message_stack
  175. truncate_echo_area
  176. truncate_message_1
  177. set_message
  178. set_message_1
  179. clear_message
  180. clear_garbaged_frames
  181. echo_area_display
  182. window_buffer_changed
  183. mode_line_update_needed
  184. window_frozen_p
  185. format_mode_line_unwind_data
  186. unwind_format_mode_line
  187. store_mode_line_noprop_char
  188. store_mode_line_noprop
  189. gui_consider_frame_title
  190. needs_no_redisplay
  191. prepare_menu_bars
  192. update_menu_bar
  193. restore_selected_window
  194. restore_frame_selected_window
  195. update_tab_bar
  196. display_tab_bar
  197. build_desired_tab_bar_string
  198. display_tab_bar_line
  199. tab_bar_height
  200. redisplay_tab_bar
  201. tab_bar_item_info
  202. get_tab_bar_item
  203. get_tab_bar_item_kbd
  204. handle_tab_bar_click
  205. note_tab_bar_highlight
  206. tty_get_tab_bar_item
  207. tty_handle_tab_bar_click
  208. update_tool_bar
  209. build_desired_tool_bar_string
  210. display_tool_bar_line
  211. tool_bar_height
  212. redisplay_tool_bar
  213. tool_bar_item_info
  214. get_tool_bar_item
  215. handle_tool_bar_click_with_device
  216. handle_tool_bar_click
  217. note_tool_bar_highlight
  218. hscroll_window_tree
  219. hscroll_windows
  220. debug_method_add
  221. text_outside_line_unchanged_p
  222. redisplay
  223. overlay_arrow_string_or_property
  224. overlay_arrow_in_current_buffer_p
  225. overlay_arrows_changed_p
  226. update_overlay_arrows
  227. overlay_arrow_at_row
  228. check_point_in_composition
  229. reconsider_clip_changes
  230. propagate_buffer_redisplay
  231. redisplay_internal
  232. unwind_redisplay_preserve_echo_area
  233. redisplay_preserve_echo_area
  234. unwind_redisplay
  235. unwind_display_working_on_window
  236. mark_window_display_accurate_1
  237. mark_window_display_accurate
  238. disp_char_vector
  239. block_buffer_flips
  240. unblock_buffer_flips
  241. buffer_flipping_blocked_p
  242. redisplay_windows
  243. redisplay_window_error
  244. redisplay_window_0
  245. redisplay_window_1
  246. update_redisplay_ticks
  247. set_cursor_from_row
  248. run_window_scroll_functions
  249. cursor_row_fully_visible_p
  250. try_scrolling
  251. compute_window_start_on_continuation_line
  252. try_cursor_movement
  253. set_vertical_scroll_bar
  254. set_horizontal_scroll_bar
  255. window_start_acceptable_p
  256. DEFUN
  257. redisplay_window
  258. try_window
  259. try_window_reusing_current_matrix
  260. find_last_row_displaying_text
  261. find_last_unchanged_at_beg_row
  262. find_first_unchanged_at_end_row
  263. sync_frame_with_window_matrix_rows
  264. row_containing_pos
  265. try_window_id
  266. dump_glyph_row
  267. dump_glyph
  268. dump_glyph_row
  269. DEFUN
  270. DEFUN
  271. DEFUN
  272. get_overlay_arrow_glyph_row
  273. insert_left_trunc_glyphs
  274. row_hash
  275. compute_line_metrics
  276. clear_position
  277. append_space_for_newline
  278. extend_face_to_end_of_line
  279. trailing_whitespace_p
  280. highlight_trailing_whitespace
  281. row_for_charpos_p
  282. cursor_row_p
  283. push_prefix_prop
  284. get_it_property
  285. get_line_prefix_it_property
  286. handle_line_prefix
  287. unproduce_glyphs
  288. find_row_edges
  289. display_count_lines_logically
  290. display_count_lines_visually
  291. maybe_produce_line_number
  292. should_produce_line_number
  293. row_text_area_empty
  294. display_line
  295. DEFUN
  296. DEFUN
  297. DEFUN
  298. display_menu_bar
  299. deep_copy_glyph_row
  300. display_tty_menu_item
  301. redisplay_mode_lines
  302. display_mode_lines
  303. display_mode_line
  304. move_elt_to_front
  305. safe_set_text_properties
  306. display_mode_element
  307. store_mode_line_string
  308. pint2str
  309. pint2hrstr
  310. decode_mode_spec_coding
  311. percent99
  312. decode_mode_spec
  313. count_lines
  314. display_count_lines
  315. display_string
  316. invisible_prop
  317. DEFUN
  318. calc_pixel_width_or_height
  319. get_font_ascent_descent
  320. dump_glyph_string
  321. init_glyph_string
  322. append_glyph_string_lists
  323. prepend_glyph_string_lists
  324. append_glyph_string
  325. get_char_face_and_encoding
  326. get_glyph_face_and_encoding
  327. get_char_glyph_code
  328. fill_composite_glyph_string
  329. fill_gstring_glyph_string
  330. fill_glyphless_glyph_string
  331. fill_glyph_string
  332. fill_image_glyph_string
  333. fill_xwidget_glyph_string
  334. fill_stretch_glyph_string
  335. get_per_char_metric
  336. normal_char_ascent_descent
  337. normal_char_height
  338. gui_get_glyph_overhangs
  339. left_overwritten
  340. left_overwriting
  341. right_overwritten
  342. right_overwriting
  343. set_glyph_string_background_width
  344. glyph_string_containing_background_width
  345. compute_overhangs_and_x
  346. draw_glyphs
  347. font_for_underline_metrics
  348. append_glyph
  349. append_composite_glyph
  350. take_vertical_position_into_account
  351. produce_image_glyph
  352. produce_xwidget_glyph
  353. append_stretch_glyph
  354. produce_stretch_glyph
  355. produce_special_glyphs
  356. pad_mode_line
  357. calc_line_height_property
  358. append_glyphless_glyph
  359. produce_glyphless_glyph
  360. gui_produce_glyphs
  361. gui_write_glyphs
  362. gui_insert_glyphs
  363. gui_clear_end_of_line
  364. get_specified_cursor_type
  365. set_frame_cursor_types
  366. get_window_cursor_type
  367. notice_overwritten_cursor
  368. gui_fix_overlapping_area
  369. draw_phys_cursor_glyph
  370. erase_phys_cursor
  371. display_and_set_cursor
  372. update_window_cursor
  373. update_cursor_in_window_tree
  374. gui_update_cursor
  375. gui_clear_cursor
  376. draw_row_with_mouse_face
  377. show_mouse_face
  378. clear_mouse_face
  379. coords_in_mouse_face_p
  380. cursor_in_mouse_face_p
  381. rows_from_pos_range
  382. mouse_face_from_buffer_pos
  383. fast_find_string_pos
  384. mouse_face_from_string_pos
  385. on_hot_spot_p
  386. find_hot_spot
  387. define_frame_cursor1
  388. note_mode_line_or_margin_highlight
  389. note_mouse_highlight
  390. gui_clear_window_mouse_face
  391. cancel_mouse_face
  392. expose_area
  393. expose_line
  394. expose_overlaps
  395. phys_cursor_in_rect_p
  396. gui_draw_vertical_border
  397. gui_draw_right_divider
  398. gui_draw_bottom_divider
  399. expose_window
  400. expose_window_tree
  401. expose_frame
  402. gui_intersect_rectangles
  403. gui_union_rectangles
  404. syms_of_xdisp
  405. init_xdisp
  406. show_hourglass
  407. start_hourglass
  408. cancel_hourglass
  409. adjust_glyph_width_for_mouse_face
  410. get_cursor_offset_for_mouse_face

     1 /* Display generation from window structure and buffer text.
     2 
     3 Copyright (C) 1985-2023 Free Software Foundation, Inc.
     4 
     5 This file is part of GNU Emacs.
     6 
     7 GNU Emacs is free software: you can redistribute it and/or modify
     8 it under the terms of the GNU General Public License as published by
     9 the Free Software Foundation, either version 3 of the License, or (at
    10 your option) any later version.
    11 
    12 GNU Emacs is distributed in the hope that it will be useful,
    13 but WITHOUT ANY WARRANTY; without even the implied warranty of
    14 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    15 GNU General Public License for more details.
    16 
    17 You should have received a copy of the GNU General Public License
    18 along with GNU Emacs.  If not, see <https://www.gnu.org/licenses/>.  */
    19 
    20 /* New redisplay written by Gerd Moellmann <gerd@gnu.org>.
    21 
    22    Redisplay.
    23 
    24    Emacs separates the task of updating the display -- which we call
    25    "redisplay" -- from the code modifying global state, e.g. buffer
    26    text.  This way functions operating on buffers don't also have to
    27    be concerned with updating the display as result of their
    28    operations.
    29 
    30    Redisplay is triggered by the Lisp interpreter when it decides it's
    31    time to do it.  This is done either automatically for you as part
    32    of the interpreter's command loop, or as the result of calling Lisp
    33    functions like `sit-for'.  The C function `redisplay_internal' in
    34    xdisp.c is the only entry into the inner redisplay code.
    35 
    36    The following diagram shows how redisplay code is invoked.  As you
    37    can see, Lisp calls redisplay and vice versa.
    38 
    39    Under window systems like X, some portions of the redisplay code
    40    are also called asynchronously, due to mouse movement or expose
    41    events.  "Asynchronously" in this context means that any C function
    42    which calls maybe_quit or process_pending_signals could enter
    43    redisplay via expose_frame and/or note_mouse_highlight, if X events
    44    were recently reported to Emacs about mouse movements or frame(s)
    45    that were exposed.  And such redisplay could invoke the Lisp
    46    interpreter, e.g. via the :eval forms in mode-line-format, and as
    47    result the global state could change.  It is therefore very
    48    important that C functions which might cause such "asynchronous"
    49    redisplay, but cannot tolerate the results, use
    50    block_input/unblock_input around code fragments which assume that
    51    global Lisp state doesn't change.  If you don't follow this rule,
    52    you will encounter bugs which are very hard to explain.  One place
    53    that needs to take such precautions is timer_check, some of whose
    54    code cannot tolerate changes in timer alists while it processes
    55    timers.
    56 
    57    +--------------+   redisplay     +----------------+
    58    | Lisp machine |---------------->| Redisplay code |<--+
    59    +--------------+   (xdisp.c)     +----------------+   |
    60           ^                                  |           |
    61           +----------------------------------+           |
    62             Block input to prevent this when             |
    63             called asynchronously!                       |
    64                                                          |
    65                     note_mouse_highlight (asynchronous)  |
    66                                                          |
    67                                     X mouse events  -----+
    68                                                          |
    69                             expose_frame (asynchronous)  |
    70                                                          |
    71                                    X expose events  -----+
    72 
    73    What does redisplay do?  Obviously, it has to figure out somehow what
    74    has been changed since the last time the display has been updated,
    75    and to make these changes visible.  Preferably it would do that in
    76    a moderately intelligent way, i.e. fast.
    77 
    78    At its highest level, redisplay can be divided into 3 distinct
    79    steps, all of which are visible in `redisplay_internal':
    80 
    81     . decide which frames need their windows to be considered for redisplay
    82     . for each window whose display might need to be updated, compute
    83       a structure, called "glyph matrix", which describes how it
    84       should look on display
    85     . actually update the display of windows on the glass where the
    86       newly obtained glyph matrix differs from the one produced by the
    87       previous redisplay cycle
    88 
    89    The first of these steps is done by `redisplay_internal' itself, by
    90    looping through all the frames and testing their various flags,
    91    such as their visibility.  The result of this could be that only
    92    the selected window on the selected frame must be redisplayed, or
    93    it could conclude that other windows need to be considered as well.
    94 
    95    The second step considers each window that might need to be
    96    redisplayed.  This could be only the selected window, or the window
    97    trees of one or more frames.  The function which considers a window
    98    and decides whether it actually needs redisplay is
    99    `redisplay_window'.  It does so by looking at the changes in
   100    position of point, in buffer text, in text properties, overlays,
   101    etc.  These changes can be deduced from window and buffer
   102    structures, and from some global variables like `beg_unchanged' and
   103    `end_unchanged'.  The current contents of the display are recorded
   104    in a `glyph matrix', a two-dimensional matrix of glyph structures.
   105    Each row in such a matrix corresponds to a line on the display, and
   106    each glyph in a row corresponds to a column displaying a character,
   107    an image, or what else.  This matrix is called the `current glyph
   108    matrix', or `current matrix', in redisplay terminology.
   109 
   110    For buffer parts that have been changed since the last redisplay,
   111    `redisplay_window' constructs a second glyph matrix, the so called
   112    `desired glyph matrix' or short `desired matrix'.  It does so in
   113    the most optimal way possible, avoiding the examination of text
   114    that didn't change, reusing portions of the current matrix if
   115    possible, etc.  It could, in particular, decide that a window
   116    doesn't need to be redisplayed at all.
   117 
   118    This second step of redisplay also updates the parts of the desired
   119    matrix that correspond to the mode lines, header lines, and
   120    tab-lines of the windows which need that; see `display_mode_lines'.
   121 
   122    In the third and last step, the current and desired matrix are then
   123    compared to find a cheap way to update the display, e.g. by reusing
   124    part of the display by scrolling lines.  The actual update of the
   125    display of each window, by comparing the desired and the current
   126    matrix, is done by `update_window', which calls functions which
   127    draw to the glass (those functions are specific to the type of the
   128    window's frame: X, w32, NS, etc.).
   129 
   130    Once the display of a window on the glass has been updated, its
   131    desired matrix is used to update the corresponding rows of the
   132    current matrix, and then the desired matrix is discarded.
   133 
   134    You will find a lot of redisplay optimizations when you start
   135    looking at the innards of `redisplay_window'.  The overall goal of
   136    all these optimizations is to make redisplay fast because it is
   137    done frequently.  Some of these optimizations are implemented by
   138    the following functions:
   139 
   140     . try_cursor_movement
   141 
   142       This optimization is applicable if the text in the window did
   143       not change and did not scroll, only point moved, and it did not
   144       move off the displayed portion of the text.  In that case, the
   145       window's glyph matrix is still valid, and only the position of
   146       the cursor might need to be updated.
   147 
   148     . try_window_reusing_current_matrix
   149 
   150       This function reuses the current glyph matrix of a window when
   151       text has not changed, but the window start changed (e.g., due to
   152       scrolling).
   153 
   154     . try_window_id
   155 
   156       This function attempts to update a window's glyph matrix by
   157       reusing parts of its current glyph matrix.  It finds and reuses
   158       the part that was not changed, and regenerates the rest.  (The
   159       "id" part in the function's name stands for "insert/delete", not
   160       for "identification" or somesuch.)
   161 
   162     . try_window
   163 
   164       This function performs the full, unoptimized, generation of a
   165       single window's glyph matrix, assuming that its fonts were not
   166       changed and that the cursor will not end up in the scroll
   167       margins.  (Loading fonts requires re-adjustment of dimensions of
   168       glyph matrices, which makes this method impossible to use.)
   169 
   170    The optimizations are tried in sequence (some can be skipped if
   171    it is known that they are not applicable).  If none of the
   172    optimizations were successful, redisplay calls redisplay_windows,
   173    which performs a full redisplay of all windows.
   174 
   175    Note that there's one more important optimization up Emacs's
   176    sleeve, but it is related to actually redrawing the potentially
   177    changed portions of the window/frame as part of the third step, not
   178    to generating the desired matrices of those potentially changed
   179    portions.  Namely, the function `update_frame' and its subroutines,
   180    which you will find in dispnew.c, compare the desired matrices with
   181    the current matrices, and only redraw the portions that changed.
   182    So it could happen that the functions in this file for some reason
   183    decide that the entire desired matrix needs to be regenerated from
   184    scratch, and still only parts of the Emacs display, or even nothing
   185    at all, will be actually delivered to the glass, because
   186    `update_frame' has found that the new and the old screen contents
   187    are similar or identical.
   188 
   189    Desired matrices.
   190 
   191    Desired matrices are always built per Emacs window.  It is
   192    important to know that a desired matrix is in general "sparse": it
   193    only has some of the glyph rows "enabled".  This is because
   194    redisplay tries to optimize its work, and thus only generates
   195    glyphs for rows that need to be updated on the screen.  Rows that
   196    don't need to be updated are left "disabled", and their contents
   197    in the desired matrix should be ignored.
   198 
   199    The function `display_line' is the central function to look at if
   200    you are interested in how the rows of the desired matrix are
   201    produced.  It constructs one row in a desired matrix given an
   202    iterator structure containing both a buffer position and a
   203    description of the environment in which the text is to be
   204    displayed.  But this is too early, read on.
   205 
   206    Glyph rows.
   207 
   208    A glyph row is an array of `struct glyph', where each glyph element
   209    describes a "display element" to be shown on the screen.  More
   210    accurately, a glyph row can have up to 3 different arrays of
   211    glyphs: one each for every display margins, and one for the "text
   212    area", where buffer text is displayed.  The text-area glyph array
   213    is always present, whereas the arrays for the marginal areas are
   214    present (non-empty) only if the corresponding display margin is
   215    shown in the window.  If the glyph array for a marginal area is not
   216    present its beginning and end coincide, i.e. such arrays are
   217    actually empty (they contain no glyphs).  Frame glyph matrices, used
   218    on text-mode terminals (see below) never have marginal areas; they
   219    treat the entire frame-wide row of glyphs as a single large "text
   220    area".
   221 
   222    Iteration over buffer and strings.
   223 
   224    Characters and pixmaps displayed for a range of buffer text depend
   225    on various settings of buffers and windows, on overlays and text
   226    properties, on display tables, on selective display.  The good news
   227    is that all this hairy stuff is hidden behind a small set of
   228    interface functions taking an iterator structure (`struct it')
   229    argument.
   230 
   231    Iteration over things to be displayed is then simple.  It is
   232    started by initializing an iterator with a call to `init_iterator',
   233    passing it the buffer position where to start iteration.  For
   234    iteration over strings, pass -1 as the position to `init_iterator',
   235    and call `reseat_to_string' when the string is ready, to initialize
   236    the iterator for that string.  Thereafter, calls to
   237    `get_next_display_element' fill the iterator structure with
   238    relevant information about the next thing to display.  Calls to
   239    `set_iterator_to_next' move the iterator to the next thing.
   240 
   241    Besides this, an iterator also contains information about the
   242    display environment in which glyphs for display elements are to be
   243    produced.  It has fields for the width and height of the display,
   244    the information whether long lines are truncated or continued, a
   245    current X and Y position, the face currently in effect, and lots of
   246    other stuff you can better see in dispextern.h.
   247 
   248    The "stop position".
   249 
   250    Some of the fields maintained by the iterator change relatively
   251    infrequently.  These include the face of the characters, whether
   252    text is invisible, the object (buffer or display or overlay string)
   253    being iterated, character composition info, etc.  For any given
   254    buffer or string position, the sources of information that affects
   255    the display can be determined by calling the appropriate
   256    primitives, such as `Fnext_single_property_change', but both these
   257    calls and the processing of their return values is relatively
   258    expensive.  To optimize redisplay, the display engine checks these
   259    sources of display information only when needed, not for every
   260    character.  To that end, it always maintains the position of the
   261    next place where it must stop and re-examine all those potential
   262    sources.  This is called "the stop position" and is stored in the
   263    `stop_charpos' field of the iterator.  The stop position is updated
   264    by `compute_stop_pos', which is called whenever the iteration
   265    reaches the current stop position and processes it.  Processing a
   266    stop position is done by `handle_stop', which invokes a series of
   267    handlers, one each for every potential source of display-related
   268    information; see the `it_props' array for those handlers.  For
   269    example, one handler is `handle_face_prop', which detects changes
   270    in face properties, and supplies the face ID that the iterator will
   271    use for all the glyphs it generates up to the next stop position;
   272    this face ID is the result of "realizing" the face specified by the
   273    relevant text properties at this position (see xfaces.c).  Each
   274    handler called by `handle_stop' processes the sources of display
   275    information for which it is "responsible", and returns a value
   276    which tells `handle_stop' what to do next.
   277 
   278    Once `handle_stop' returns, the information it stores in the
   279    iterator fields will not be refreshed until the iteration reaches
   280    the next stop position, which is computed by `compute_stop_pos'
   281    called at the end of `handle_stop'.  `compute_stop_pos' examines
   282    the buffer's or string's interval tree to determine where the text
   283    properties change, finds the next position where overlays and
   284    character composition can change, and stores in `stop_charpos' the
   285    closest position where any of these factors should be reconsidered.
   286 
   287    Handling of the stop position is done as part of the code in
   288    `get_next_display_element'.
   289 
   290    Producing glyphs.
   291 
   292    Glyphs in a desired matrix are normally constructed in a loop
   293    calling `get_next_display_element' and then `PRODUCE_GLYPHS'.  The
   294    call to `PRODUCE_GLYPHS' will fill the iterator structure with
   295    pixel information about the element being displayed and at the same
   296    time will produce glyphs for it.  If the display element fits on
   297    the line being displayed, `set_iterator_to_next' is called next,
   298    otherwise the glyphs produced are discarded, and `display_line'
   299    marks this glyph row as a "continued line".  The function
   300    `display_line' is the workhorse of filling glyph rows in the
   301    desired matrix with glyphs.  In addition to producing glyphs, it
   302    also handles line truncation and continuation, word wrap, and
   303    cursor positioning (for the latter, see `set_cursor_from_row').
   304 
   305    Frame matrices.
   306 
   307    That just couldn't be all, could it?  What about terminal types not
   308    supporting operations on sub-windows of the screen (a.k.a. "TTY" or
   309    "text-mode terminals")?  To update the display on such a terminal,
   310    window-based glyph matrices are not well suited.  To be able to
   311    reuse part of the display (scrolling lines up and down), we must
   312    instead have a view of the whole screen.  This is what `frame
   313    matrices' are for.  They are a trick.
   314 
   315    Frames on text terminals have a glyph pool.  Windows on such a
   316    frame sub-allocate their glyph memory from their frame's glyph
   317    pool.  The frame itself is given its own glyph matrices.  By
   318    coincidence---or maybe something else---rows in window glyph
   319    matrices are slices of corresponding rows in frame matrices.  Thus
   320    writing to window matrices implicitly updates a frame matrix which
   321    provides us with the view of the whole screen that we originally
   322    wanted to have without having to move many bytes around.  Then
   323    updating all the visible windows on text-terminal frames is done by
   324    using the frame matrices, which allows frame-global optimization of
   325    what is actually written to the glass.
   326 
   327    Frame matrices don't have marginal areas, only a text area.  That
   328    is, the entire row of glyphs that spans the width of a text-mode
   329    frame is treated as a single large "text area" for the purposes of
   330    manipulating and updating a frame glyph matrix.
   331 
   332    To be honest, there is a little bit more done for frame matrices,
   333    but not much more.  If you plan to extend that code, take a look at
   334    dispnew.c.  The function build_frame_matrix is a good starting
   335    point.
   336 
   337    Simulating display.
   338 
   339    Some of Emacs commands and functions need to take display layout
   340    into consideration.  For example, C-n moves to the next screen
   341    line, but to implement that, Emacs needs to find the buffer
   342    position which is directly below the cursor position on display.
   343    This is not trivial when buffer display includes variable-size
   344    elements such as different fonts, tall images, etc.
   345 
   346    To solve this problem, the display engine implements several
   347    functions that can move through buffer text in the same manner as
   348    `display_line' and `display_string' do, but without producing any
   349    glyphs for the glyph matrices.  The workhorse of this is
   350    `move_it_in_display_line_to'.  Its code and logic are very similar
   351    to `display_line', but it differs in two important aspects: it
   352    doesn't produce glyphs for any glyph matrix, and it returns a
   353    status telling the caller how it ended the iteration: whether it
   354    reached the required position, hit the end of line, arrived at the
   355    window edge without exhausting the buffer's line, etc.  Since the
   356    glyphs are not produced, the layout information available to the
   357    callers of this function is what is recorded in `struct it' by the
   358    iteration process.
   359 
   360    Several higher-level functions call `move_it_in_display_line_to' to
   361    perform more complex tasks: `move_it_by_lines' can move N lines up
   362    or down from a given buffer position and `move_it_to' can move to a
   363    given buffer position or to a given X or Y pixel coordinate.
   364 
   365    These functions are called by the display engine itself as well,
   366    when it needs to make layout decisions before producing the glyphs.
   367    For example, one of the first things to decide when redisplaying a
   368    window is where to put the `window-start' position; if the window
   369    is to be recentered (the default), Emacs makes that decision by
   370    starting from the position of point, then moving up the number of
   371    lines corresponding to half the window height using
   372    `move_it_by_lines'.
   373 
   374    Bidirectional display.
   375 
   376    Bidirectional display adds quite some hair to this already complex
   377    design.  The good news are that a large portion of that hairy stuff
   378    is hidden in bidi.c behind only 3 interfaces.  bidi.c implements a
   379    reordering engine which is called by `set_iterator_to_next' and
   380    returns the next character to display in the visual order.  See
   381    commentary on bidi.c for more details.  As far as redisplay is
   382    concerned, the effect of calling `bidi_move_to_visually_next', the
   383    main interface of the reordering engine, is that the iterator gets
   384    magically placed on the buffer or string position that is to be
   385    displayed next in the visual order.  In other words, a linear
   386    iteration through the buffer/string is replaced with a non-linear
   387    one.  All the rest of the redisplay is oblivious to the bidi
   388    reordering.
   389 
   390    Well, almost oblivious---there are still complications, most of
   391    them due to the fact that buffer and string positions no longer
   392    change monotonously with glyph indices in a glyph row.  Moreover,
   393    for continued lines, the buffer positions may not even be
   394    monotonously changing with vertical positions.  Also, accounting
   395    for face changes, overlays, etc. becomes more complex because
   396    non-linear iteration could potentially skip many positions with
   397    such changes, and then cross them again on the way back (see
   398    `handle_stop_backwards')...
   399 
   400    One other prominent effect of bidirectional display is that some
   401    paragraphs of text need to be displayed starting at the right
   402    margin of the window---the so-called right-to-left, or R2L
   403    paragraphs.  R2L paragraphs are displayed with R2L glyph rows,
   404    which have their `reversed_p' flag set.  The bidi reordering engine
   405    produces characters in such rows starting from the character which
   406    should be the rightmost on display.  `PRODUCE_GLYPHS' then reverses
   407    the order, when it fills up the glyph row whose `reversed_p' flag
   408    is set, by prepending each new glyph to what is already there,
   409    instead of appending it.  When the glyph row is complete, the
   410    function `extend_face_to_end_of_line' fills the empty space to the
   411    left of the leftmost character with special glyphs, which will
   412    display as, well, empty.  On text terminals, these special glyphs
   413    are simply blank characters.  On graphics terminals, there's a
   414    single stretch glyph of a suitably computed width.  Both the blanks
   415    and the stretch glyph are given the face of the background of the
   416    line.  This way, the terminal-specific back-end can still draw the
   417    glyphs left to right, even for R2L lines.
   418 
   419    Bidirectional display and character compositions.
   420 
   421    Some scripts cannot be displayed by drawing each character
   422    individually, because adjacent characters change each other's shape
   423    on display.  For example, Arabic and Indic scripts belong to this
   424    category.
   425 
   426    Emacs display supports this by providing "character compositions",
   427    most of which is implemented in composite.c.  During the buffer
   428    scan that delivers characters to `PRODUCE_GLYPHS', if the next
   429    character to be delivered is a composed character, the iteration
   430    calls `composition_reseat_it' and `next_element_from_composition'.
   431    If they succeed to compose the character with one or more of the
   432    following characters, the whole sequence of characters that were
   433    composed is recorded in the `struct composition_it' object that is
   434    part of the buffer iterator.  The composed sequence could produce
   435    one or more font glyphs (called "grapheme clusters") on the screen.
   436    Each of these grapheme clusters is then delivered to
   437    `PRODUCE_GLYPHS' in the direction corresponding to the current bidi
   438    scan direction (recorded in the `scan_dir' member of the `struct
   439    bidi_it' object that is part of the iterator).  In particular, if
   440    the bidi iterator currently scans the buffer backwards, the
   441    grapheme clusters are delivered back to front.  This reorders the
   442    grapheme clusters as appropriate for the current bidi context.
   443    Note that this means that the grapheme clusters are always stored
   444    in the `LGSTRING' object (see composite.c) in the logical order.
   445 
   446    Moving an iterator in bidirectional text
   447    without producing glyphs.
   448 
   449    Note one important detail mentioned above: that the bidi reordering
   450    engine, driven by the iterator, produces characters in R2L rows
   451    starting at the character that will be the rightmost on display.
   452    As far as the iterator is concerned, the geometry of such rows is
   453    still left to right, i.e. the iterator "thinks" the first character
   454    is at the leftmost pixel position.  The iterator does not know that
   455    `PRODUCE_GLYPHS' reverses the order of the glyphs that the iterator
   456    delivers.  This is important when functions from the `move_it_*'
   457    family are used to get to certain screen position or to match
   458    screen coordinates with buffer coordinates: these functions use the
   459    iterator geometry, which is left to right even in R2L paragraphs.
   460    This works well with most callers of `move_it_*', because they need
   461    to get to a specific column, and columns are still numbered in the
   462    reading order, i.e. the rightmost character in a R2L paragraph is
   463    still column zero.  But some callers do not get well with this; a
   464    notable example is mouse clicks that need to find the character
   465    that corresponds to certain pixel coordinates.  See
   466    `buffer_posn_from_coords' in dispnew.c for how this is handled.  */
   467 
   468 #include <config.h>
   469 #include <stdlib.h>
   470 #include <limits.h>
   471 #include <math.h>
   472 
   473 #include "lisp.h"
   474 #include "atimer.h"
   475 #include "composite.h"
   476 #include "keyboard.h"
   477 #include "sysstdio.h"
   478 #include "systime.h"
   479 #include "frame.h"
   480 #include "window.h"
   481 #include "termchar.h"
   482 #include "dispextern.h"
   483 #include "character.h"
   484 #include "category.h"
   485 #include "buffer.h"
   486 #include "charset.h"
   487 #include "indent.h"
   488 #include "commands.h"
   489 #include "keymap.h"
   490 #include "disptab.h"
   491 #include "termhooks.h"
   492 #include "termopts.h"
   493 #include "intervals.h"
   494 #include "coding.h"
   495 #include "region-cache.h"
   496 #include "font.h"
   497 #include "fontset.h"
   498 #include "blockinput.h"
   499 #include "xwidget.h"
   500 #ifdef HAVE_WINDOW_SYSTEM
   501 #include TERM_HEADER
   502 #endif /* HAVE_WINDOW_SYSTEM */
   503 
   504 #ifndef FRAME_OUTPUT_DATA
   505 #define FRAME_OUTPUT_DATA(f) (NULL)
   506 #endif
   507 
   508 #define DISP_INFINITY 10000000
   509 
   510 /* Holds the list (error).  */
   511 static Lisp_Object list_of_error;
   512 
   513 #ifdef HAVE_WINDOW_SYSTEM
   514 
   515 /* Test if overflow newline into fringe.  Called with iterator IT
   516    at or past right window margin, and with IT->current_x set.  */
   517 
   518 #define IT_OVERFLOW_NEWLINE_INTO_FRINGE(IT)             \
   519   (!NILP (Voverflow_newline_into_fringe)                \
   520    && FRAME_WINDOW_P ((IT)->f)                          \
   521    && ((IT)->bidi_it.paragraph_dir == R2L               \
   522        ? (WINDOW_LEFT_FRINGE_WIDTH ((IT)->w) > 0)       \
   523        : (WINDOW_RIGHT_FRINGE_WIDTH ((IT)->w) > 0))     \
   524    && (IT)->current_x == (IT)->last_visible_x)
   525 
   526 #else /* !HAVE_WINDOW_SYSTEM */
   527 #define IT_OVERFLOW_NEWLINE_INTO_FRINGE(it) false
   528 #endif /* HAVE_WINDOW_SYSTEM */
   529 
   530 /* Test if the display element loaded in IT, or the underlying buffer
   531    or string character, is a space or a TAB character.  This is used
   532    to determine where word wrapping can occur.  */
   533 
   534 #define IT_DISPLAYING_WHITESPACE(it)                                    \
   535   ((it->what == IT_CHARACTER && (it->c == ' ' || it->c == '\t'))        \
   536    || ((STRINGP (it->string)                                            \
   537         && (SREF (it->string, IT_STRING_BYTEPOS (*it)) == ' '           \
   538             || SREF (it->string, IT_STRING_BYTEPOS (*it)) == '\t'))     \
   539        || (it->s                                                        \
   540            && (it->s[IT_BYTEPOS (*it)] == ' '                           \
   541                || it->s[IT_BYTEPOS (*it)] == '\t'))                     \
   542        || (IT_BYTEPOS (*it) < ZV_BYTE                                   \
   543            && (*BYTE_POS_ADDR (IT_BYTEPOS (*it)) == ' '                 \
   544                || *BYTE_POS_ADDR (IT_BYTEPOS (*it)) == '\t'))))
   545 
   546 /* These are the category sets we use.  They are defined by
   547    kinsoku.el and characters.el.  */
   548 #define NOT_AT_EOL '<'
   549 #define NOT_AT_BOL '>'
   550 #define LINE_BREAKABLE '|'
   551 
   552 static bool
   553 it_char_has_category(struct it *it, int cat)
   554 {
   555   int ch = 0;
   556   if (it->what == IT_CHARACTER)
   557     ch = it->c;
   558   else if (STRINGP (it->string))
   559     ch = SREF (it->string, IT_STRING_BYTEPOS (*it));
   560   else if (it->s)
   561     ch = it->s[IT_BYTEPOS (*it)];
   562   else if (IT_BYTEPOS (*it) < ZV_BYTE)
   563     ch = *BYTE_POS_ADDR (IT_BYTEPOS (*it));
   564 
   565   if (ch == 0)
   566     return false;
   567   else
   568     return CHAR_HAS_CATEGORY (ch, cat);
   569 }
   570 
   571 /* Return true if the current character allows wrapping before it.   */
   572 static bool
   573 char_can_wrap_before (struct it *it)
   574 {
   575   if (!word_wrap_by_category)
   576     return !IT_DISPLAYING_WHITESPACE (it);
   577 
   578   /* For CJK (LTR) text in RTL paragraph, EOL and BOL are flipped.
   579      Because in RTL paragraph, each glyph is prepended to the last
   580      one, effectively drawing right to left.  */
   581   int not_at_bol;
   582   if (it->glyph_row && it->glyph_row->reversed_p)
   583     not_at_bol = NOT_AT_EOL;
   584   else
   585     not_at_bol = NOT_AT_BOL;
   586   /* You cannot wrap before a space or tab because that way you'll
   587      have space and tab at the beginning of next line.  */
   588   return (!IT_DISPLAYING_WHITESPACE (it)
   589           /* Can be at BOL.  */
   590           && !it_char_has_category (it, not_at_bol));
   591 }
   592 
   593 /* Return true if the current character allows wrapping after it.   */
   594 static bool
   595 char_can_wrap_after (struct it *it)
   596 {
   597   if (!word_wrap_by_category)
   598     return IT_DISPLAYING_WHITESPACE (it);
   599 
   600   /* For CJK (LTR) text in RTL paragraph, EOL and BOL are flipped.
   601      Because in RTL paragraph, each glyph is prepended to the last
   602      one, effectively drawing right to left.  */
   603   int not_at_eol;
   604   if (it->glyph_row && it->glyph_row->reversed_p)
   605     not_at_eol = NOT_AT_BOL;
   606   else
   607     not_at_eol = NOT_AT_EOL;
   608 
   609   return (IT_DISPLAYING_WHITESPACE (it)
   610           /* Can break after && can be at EOL.  */
   611           || (it_char_has_category (it, LINE_BREAKABLE)
   612               && !it_char_has_category (it, not_at_eol)));
   613 }
   614 
   615 #undef IT_DISPLAYING_WHITESPACE
   616 #undef NOT_AT_EOL
   617 #undef NOT_AT_BOL
   618 #undef LINE_BREAKABLE
   619 
   620 /* If all the conditions needed to print the fill column indicator are
   621    met, return the (nonnegative) column number, else return a negative
   622    value.  */
   623 static int
   624 fill_column_indicator_column (struct it *it, int char_width)
   625 {
   626   if (display_fill_column_indicator
   627       && !it->w->pseudo_window_p
   628       && it->continuation_lines_width == 0
   629       && CHARACTERP (Vdisplay_fill_column_indicator_character))
   630     {
   631       Lisp_Object col = (EQ (Vdisplay_fill_column_indicator_column, Qt)
   632                          ? BVAR (current_buffer, fill_column)
   633                          : Vdisplay_fill_column_indicator_column);
   634 
   635       /* The stretch width needs to consider the latter
   636          added glyph in append_space_for_newline.  */
   637       if (RANGED_FIXNUMP (0, col, INT_MAX))
   638         {
   639           int icol = XFIXNUM (col);
   640           if (!ckd_mul (&icol, icol, char_width)
   641               && !ckd_add (&icol, icol, it->lnum_pixel_width))
   642             return icol;
   643         }
   644     }
   645   return -1;
   646 }
   647 
   648 /* True means print newline to stdout before next mini-buffer message.  */
   649 
   650 bool noninteractive_need_newline;
   651 
   652 /* True means print newline to message log before next message.  */
   653 
   654 static bool message_log_need_newline;
   655 
   656 /* Three markers that message_dolog uses.
   657    It could allocate them itself, but that causes trouble
   658    in handling memory-full errors.  */
   659 static Lisp_Object message_dolog_marker1;
   660 static Lisp_Object message_dolog_marker2;
   661 static Lisp_Object message_dolog_marker3;
   662 
   663 /* The buffer position of the first character appearing entirely or
   664    partially on the line of the selected window which contains the
   665    cursor; <= 0 if not known.  Set by set_cursor_from_row, used for
   666    redisplay optimization in redisplay_internal.  */
   667 
   668 static struct text_pos this_line_start_pos;
   669 
   670 /* Number of characters past the end of the line above, including the
   671    terminating newline.  */
   672 
   673 static struct text_pos this_line_end_pos;
   674 
   675 /* The vertical positions and the height of this line.  */
   676 
   677 static int this_line_vpos;
   678 static int this_line_y;
   679 static int this_line_pixel_height;
   680 
   681 /* X position at which this display line starts.  Usually zero;
   682    negative if first character is partially visible.  */
   683 
   684 static int this_line_start_x;
   685 
   686 /* The smallest character position seen by move_it_* functions as they
   687    move across display lines.  Used to set MATRIX_ROW_START_CHARPOS of
   688    hscrolled lines, see display_line.  */
   689 
   690 static struct text_pos this_line_min_pos;
   691 
   692 /* Buffer that this_line_.* variables are referring to.  */
   693 
   694 static struct buffer *this_line_buffer;
   695 
   696 /* True if an overlay arrow has been displayed in this window.  */
   697 
   698 static bool overlay_arrow_seen;
   699 
   700 /* Vector containing glyphs for an ellipsis `...'.  */
   701 
   702 static Lisp_Object default_invis_vector[3];
   703 
   704 /* This is the window where the echo area message was displayed.  It
   705    is always a mini-buffer window, but it may not be the same window
   706    currently active as a mini-buffer.  */
   707 
   708 Lisp_Object echo_area_window;
   709 
   710 /* Stack of messages, which are pushed by push_message and popped and
   711    displayed by restore_message.  */
   712 
   713 static Lisp_Object Vmessage_stack;
   714 
   715 /* True means multibyte characters were enabled when the echo area
   716    message was specified.  */
   717 
   718 static bool message_enable_multibyte;
   719 
   720 /* At each redisplay cycle, we should refresh everything there is to refresh.
   721    To do that efficiently, we use many optimizations that try to make sure we
   722    don't waste too much time updating things that haven't changed.
   723    The coarsest such optimization is that, in the most common cases, we only
   724    look at the selected-window.
   725 
   726    To know whether other windows should be considered for redisplay, we use the
   727    variable windows_or_buffers_changed: as long as it is 0, it means that we
   728    have not noticed anything that should require updating anything else than
   729    the selected-window.  If it is set to REDISPLAY_SOME, it means that since
   730    last redisplay, some changes have been made which could impact other
   731    windows.  To know which ones need redisplay, every buffer, window, and frame
   732    has a `redisplay' bit, which (if true) means that this object needs to be
   733    redisplayed.  If windows_or_buffers_changed is 0, we know there's no point
   734    looking for those `redisplay' bits (actually, there might be some such bits
   735    set, but then only on objects which aren't displayed anyway).
   736 
   737    OTOH if it's non-zero we will have to loop through all windows and then
   738    check the `redisplay' bit of the corresponding window, frame, and buffer, in
   739    order to decide whether that window needs attention or not.  Note that we
   740    can't just look at the frame's redisplay bit to decide that the whole frame
   741    can be skipped, since even if the frame's redisplay bit is unset, some of
   742    its windows's redisplay bits may be set.
   743 
   744    Mostly for historical reasons, windows_or_buffers_changed can also take
   745    other non-zero values.  In that case, the precise value doesn't matter (it
   746    encodes the cause of the setting but is only used for debugging purposes),
   747    and what it means is that we shouldn't pay attention to any `redisplay' bits
   748    and we should simply try and redisplay every window out there.  */
   749 
   750 int windows_or_buffers_changed;
   751 
   752 /* Nonzero if we should redraw the mode lines on the next redisplay.
   753    Similarly to `windows_or_buffers_changed', if it has value REDISPLAY_SOME,
   754    then only redisplay the mode lines in those buffers/windows/frames where the
   755    `redisplay' bit has been set.
   756    For any other value, redisplay all mode lines (the number used is then only
   757    used to track down the cause for this full-redisplay).
   758 
   759    Since the frame title uses the same %-constructs as the mode line
   760    (except %c, %C, and %l), if this variable is non-zero, we also consider
   761    redisplaying the title of each frame, see gui_consider_frame_title.
   762 
   763    The `redisplay' bits are the same as those used for
   764    windows_or_buffers_changed, and setting windows_or_buffers_changed also
   765    causes recomputation of the mode lines of all those windows.  IOW this
   766    variable only has an effect if windows_or_buffers_changed is zero, in which
   767    case we should only need to redisplay the mode-line of those objects with
   768    a `redisplay' bit set but not the window's text content (tho we may still
   769    need to refresh the text content of the selected-window).  */
   770 
   771 int update_mode_lines;
   772 
   773 /* True after display_mode_line if %l was used and it displayed a
   774    line number.  */
   775 
   776 static bool line_number_displayed;
   777 
   778 /* Current, index 0, and last displayed echo area message.  Either
   779    buffers from echo_buffers, or nil to indicate no message.  */
   780 
   781 Lisp_Object echo_area_buffer[2];
   782 
   783 /* The buffers referenced from echo_area_buffer.  */
   784 
   785 static Lisp_Object echo_buffer[2];
   786 
   787 /* A vector saved used in with_area_buffer to reduce consing.  */
   788 
   789 static Lisp_Object Vwith_echo_area_save_vector;
   790 
   791 /* True means display_echo_area should display the last echo area
   792    message again.  Set by redisplay_preserve_echo_area.  */
   793 
   794 static bool display_last_displayed_message_p;
   795 
   796 /* True if echo area is being used by print; false if being used by
   797    message.  */
   798 
   799 static bool message_buf_print;
   800 
   801 /* Set to true in clear_message to make redisplay_internal aware
   802    of an emptied echo area.  */
   803 
   804 static bool message_cleared_p;
   805 
   806 /* A scratch glyph row with contents used for generating truncation
   807    glyphs and overlay-arrow glyphs.  */
   808 
   809 #define MAX_SCRATCH_GLYPHS 100
   810 static struct glyph_row scratch_glyph_row;
   811 static struct glyph scratch_glyphs[MAX_SCRATCH_GLYPHS];
   812 
   813 /* Ascent and height of the last line processed by move_it_to.  */
   814 
   815 static int last_height;
   816 
   817 /* True if there's a help-echo in the echo area.  */
   818 
   819 bool help_echo_showing_p;
   820 
   821 /* The maximum distance to look ahead for text properties.  Values
   822    that are too small let us call compute_char_face and similar
   823    functions too often which is expensive.  Values that are too large
   824    let us call compute_char_face and alike too often because we
   825    might not be interested in text properties that far away.  */
   826 
   827 #define TEXT_PROP_DISTANCE_LIMIT 100
   828 
   829 /* SAVE_IT and RESTORE_IT are called when we save a snapshot of the
   830    iterator state and later restore it.  This is needed because the
   831    bidi iterator on bidi.c keeps a stacked cache of its states, which
   832    is really a singleton.  When we use scratch iterator objects to
   833    move around the buffer, we can cause the bidi cache to be pushed or
   834    popped, and therefore we need to restore the cache state when we
   835    return to the original iterator.  */
   836 #define SAVE_IT(ITCOPY, ITORIG, CACHE)          \
   837   do {                                          \
   838     if (CACHE)                                  \
   839       bidi_unshelve_cache (CACHE, true);        \
   840     ITCOPY = ITORIG;                            \
   841     CACHE = bidi_shelve_cache ();               \
   842   } while (false)
   843 
   844 #define RESTORE_IT(pITORIG, pITCOPY, CACHE)     \
   845   do {                                          \
   846     if (pITORIG != pITCOPY)                     \
   847       *(pITORIG) = *(pITCOPY);                  \
   848     bidi_unshelve_cache (CACHE, false);         \
   849     CACHE = NULL;                               \
   850   } while (false)
   851 
   852 /* Functions to mark elements as needing redisplay.  */
   853 enum { REDISPLAY_SOME = 2};     /* Arbitrary choice.  */
   854 
   855 static bool calc_pixel_width_or_height (double *, struct it *, Lisp_Object,
   856                                         struct font *, bool, int *);
   857 
   858 void
   859 redisplay_other_windows (void)
   860 {
   861   if (!windows_or_buffers_changed)
   862     windows_or_buffers_changed = REDISPLAY_SOME;
   863 }
   864 
   865 void
   866 wset_redisplay (struct window *w)
   867 {
   868   /* Beware: selected_window can be nil during early stages.  */
   869   if (!BASE_EQ (make_lisp_ptr (w, Lisp_Vectorlike), selected_window))
   870     redisplay_other_windows ();
   871   w->redisplay = true;
   872 }
   873 
   874 void
   875 fset_redisplay (struct frame *f)
   876 {
   877   redisplay_other_windows ();
   878   f->redisplay = true;
   879 }
   880 
   881 void
   882 bset_redisplay (struct buffer *b)
   883 {
   884   int count = buffer_window_count (b);
   885   if (count > 0)
   886     {
   887       /* ... it's visible in other window than selected,  */
   888       if (count > 1 || b != XBUFFER (XWINDOW (selected_window)->contents))
   889         redisplay_other_windows ();
   890       /* Even if we don't set windows_or_buffers_changed, do set `redisplay'
   891          so that if we later set windows_or_buffers_changed, this buffer will
   892          not be omitted.  */
   893       b->text->redisplay = true;
   894     }
   895 }
   896 
   897 void
   898 bset_update_mode_line (struct buffer *b)
   899 {
   900   if (!update_mode_lines)
   901     update_mode_lines = REDISPLAY_SOME;
   902   b->text->redisplay = true;
   903 }
   904 
   905 void
   906 wset_update_mode_line (struct window *w)
   907 {
   908   w->update_mode_line = true;
   909   /* When a window's mode line needs to be updated, the window's frame's
   910      title may also need to be updated, but we don't need to worry about it
   911      here.  Instead, `gui_consider_frame_title' is automatically called
   912      whenever w->update_mode_line is set for that frame's selected window.
   913      But for this to work reliably, we have to make sure the window
   914      is considered, so we have to mark it for redisplay.  */
   915   wset_redisplay (w);
   916 }
   917 
   918 DEFUN ("set-buffer-redisplay", Fset_buffer_redisplay,
   919        Sset_buffer_redisplay, 4, 4, 0,
   920        doc: /* Mark the current buffer for redisplay.
   921 This function may be passed to `add-variable-watcher'.  */)
   922   (Lisp_Object symbol, Lisp_Object newval, Lisp_Object op, Lisp_Object where)
   923 {
   924   bset_update_mode_line (current_buffer);
   925   current_buffer->prevent_redisplay_optimizations_p = true;
   926   return Qnil;
   927 }
   928 
   929 /* redisplay_trace is for displaying traces of redisplay.
   930    If Emacs was compiled with GLYPH_DEBUG defined, the variable
   931    trace_redisplay_p can be set to a non-zero value in debugging
   932    sessions to activate traces.  */
   933 #ifdef GLYPH_DEBUG
   934 extern bool trace_redisplay_p EXTERNALLY_VISIBLE;
   935 bool trace_redisplay_p;
   936 #else
   937 enum { trace_redisplay_p = false };
   938 #endif
   939 static void ATTRIBUTE_FORMAT_PRINTF (1, 2)
   940 redisplay_trace (char const *fmt, ...)
   941 {
   942   if (trace_redisplay_p)
   943     {
   944       va_list ap;
   945       va_start (ap, fmt);
   946       vprintf (fmt, ap);
   947       va_end (ap);
   948     }
   949 }
   950 
   951 #ifdef DEBUG_TRACE_MOVE
   952 extern bool trace_move EXTERNALLY_VISIBLE;
   953 bool trace_move;
   954 #else
   955 enum { trace_move = false };
   956 #endif
   957 static void ATTRIBUTE_FORMAT_PRINTF (1, 2)
   958 move_trace (char const *fmt, ...)
   959 {
   960   if (trace_move)
   961     {
   962       va_list ap;
   963       va_start (ap, fmt);
   964       vprintf (fmt, ap);
   965       va_end (ap);
   966     }
   967 }
   968 
   969 /* Buffer being redisplayed -- for redisplay_window_error.  */
   970 
   971 static struct buffer *displayed_buffer;
   972 
   973 /* Value returned from text property handlers (see below).  */
   974 
   975 enum prop_handled
   976 {
   977   HANDLED_NORMALLY,
   978   HANDLED_RECOMPUTE_PROPS,
   979   HANDLED_OVERLAY_STRING_CONSUMED,
   980   HANDLED_RETURN
   981 };
   982 
   983 /* A description of text properties that redisplay is interested
   984    in.  */
   985 
   986 struct props
   987 {
   988   /* The symbol index of the name of the property.  */
   989   short name;
   990 
   991   /* A unique index for the property.  */
   992   enum prop_idx idx;
   993 
   994   /* A handler function called to set up iterator IT from the property
   995      at IT's current position.  Value is used to steer handle_stop.  */
   996   enum prop_handled (*handler) (struct it *it);
   997 };
   998 
   999 static enum prop_handled handle_face_prop (struct it *);
  1000 static enum prop_handled handle_invisible_prop (struct it *);
  1001 static enum prop_handled handle_display_prop (struct it *);
  1002 static enum prop_handled handle_composition_prop (struct it *);
  1003 static enum prop_handled handle_overlay_change (struct it *);
  1004 static enum prop_handled handle_fontified_prop (struct it *);
  1005 
  1006 /* Properties handled by iterators.  */
  1007 
  1008 static struct props it_props[] =
  1009 {
  1010   {SYMBOL_INDEX (Qfontified),   FONTIFIED_PROP_IDX,     handle_fontified_prop},
  1011   /* Handle `face' before `display' because some sub-properties of
  1012      `display' need to know the face.  */
  1013   {SYMBOL_INDEX (Qface),        FACE_PROP_IDX,          handle_face_prop},
  1014   {SYMBOL_INDEX (Qdisplay),     DISPLAY_PROP_IDX,       handle_display_prop},
  1015   {SYMBOL_INDEX (Qinvisible),   INVISIBLE_PROP_IDX,     handle_invisible_prop},
  1016   {SYMBOL_INDEX (Qcomposition), COMPOSITION_PROP_IDX, handle_composition_prop},
  1017   {0,                           0,                      NULL}
  1018 };
  1019 
  1020 /* Enumeration returned by some move_it_.* functions internally.  */
  1021 
  1022 enum move_it_result
  1023 {
  1024   /* Not used.  Undefined value.  */
  1025   MOVE_UNDEFINED,
  1026 
  1027   /* Move ended at the requested buffer position or ZV.  */
  1028   MOVE_POS_MATCH_OR_ZV,
  1029 
  1030   /* Move ended at the requested X pixel position.  */
  1031   MOVE_X_REACHED,
  1032 
  1033   /* Move within a line ended at the end of a line that must be
  1034      continued.  */
  1035   MOVE_LINE_CONTINUED,
  1036 
  1037   /* Move within a line ended at the end of a line that would
  1038      be displayed truncated.  */
  1039   MOVE_LINE_TRUNCATED,
  1040 
  1041   /* Move within a line ended at a line end.  */
  1042   MOVE_NEWLINE_OR_CR
  1043 };
  1044 
  1045 /* This counter is used to clear the face cache every once in a while
  1046    in redisplay_internal.  It is incremented for each redisplay.
  1047    Every CLEAR_FACE_CACHE_COUNT full redisplays, the face cache is
  1048    cleared.  */
  1049 
  1050 #define CLEAR_FACE_CACHE_COUNT  500
  1051 static int clear_face_cache_count;
  1052 
  1053 /* Similarly for the image cache.  */
  1054 
  1055 #ifdef HAVE_WINDOW_SYSTEM
  1056 #define CLEAR_IMAGE_CACHE_COUNT 101
  1057 static int clear_image_cache_count;
  1058 
  1059 /* Null glyph slice */
  1060 static struct glyph_slice null_glyph_slice = { 0, 0, 0, 0 };
  1061 #endif
  1062 
  1063 /* True while redisplay_internal is in progress.  */
  1064 
  1065 bool redisplaying_p;
  1066 
  1067 /* True while some display-engine code is working on layout of some
  1068    window.
  1069 
  1070    WARNING: Use sparingly, preferably only in top level of commands
  1071    and important functions, because using it in nested calls might
  1072    reset the flag when the inner call returns, behind the back of
  1073    the callers.  */
  1074 bool display_working_on_window_p;
  1075 
  1076 /* If a string, XTread_socket generates an event to display that string.
  1077    (The display is done in read_char.)  */
  1078 
  1079 Lisp_Object help_echo_string;
  1080 Lisp_Object help_echo_window;
  1081 Lisp_Object help_echo_object;
  1082 ptrdiff_t help_echo_pos;
  1083 
  1084 /* Temporary variable for XTread_socket.  */
  1085 
  1086 Lisp_Object previous_help_echo_string;
  1087 
  1088 /* Platform-independent portion of hourglass implementation.  */
  1089 
  1090 #ifdef HAVE_WINDOW_SYSTEM
  1091 
  1092 /* True means an hourglass cursor is currently shown.  */
  1093 static bool hourglass_shown_p;
  1094 
  1095 /* If non-null, an asynchronous timer that, when it expires, displays
  1096    an hourglass cursor on all frames.  */
  1097 static struct atimer *hourglass_atimer;
  1098 
  1099 #endif /* HAVE_WINDOW_SYSTEM */
  1100 
  1101 /* Default number of seconds to wait before displaying an hourglass
  1102    cursor.  */
  1103 #define DEFAULT_HOURGLASS_DELAY 1
  1104 
  1105 #ifdef HAVE_WINDOW_SYSTEM
  1106 
  1107 /* Default pixel width of `thin-space' display method.  */
  1108 #define THIN_SPACE_WIDTH 1
  1109 
  1110 #endif /* HAVE_WINDOW_SYSTEM */
  1111 
  1112 /* Function prototypes.  */
  1113 
  1114 static void setup_for_ellipsis (struct it *, int);
  1115 static void set_iterator_to_next (struct it *, bool);
  1116 static void mark_window_display_accurate_1 (struct window *, bool);
  1117 static bool row_for_charpos_p (struct glyph_row *, ptrdiff_t);
  1118 static bool cursor_row_p (struct glyph_row *);
  1119 static int redisplay_mode_lines (Lisp_Object, bool);
  1120 
  1121 static void handle_line_prefix (struct it *);
  1122 
  1123 static void handle_stop_backwards (struct it *, ptrdiff_t);
  1124 static void unwind_with_echo_area_buffer (Lisp_Object);
  1125 static Lisp_Object with_echo_area_buffer_unwind_data (struct window *);
  1126 static bool current_message_1 (void *, Lisp_Object);
  1127 static bool truncate_message_1 (void *, Lisp_Object);
  1128 static void set_message (Lisp_Object);
  1129 static bool set_message_1 (void *, Lisp_Object);
  1130 static bool display_echo_area_1 (void *, Lisp_Object);
  1131 static bool resize_mini_window_1 (void *, Lisp_Object);
  1132 static void unwind_redisplay (void);
  1133 static void extend_face_to_end_of_line (struct it *);
  1134 static intmax_t message_log_check_duplicate (ptrdiff_t, ptrdiff_t);
  1135 static void push_it (struct it *, struct text_pos *);
  1136 static void iterate_out_of_display_property (struct it *);
  1137 static void pop_it (struct it *);
  1138 static void redisplay_internal (void);
  1139 static void echo_area_display (bool);
  1140 static void block_buffer_flips (void);
  1141 static void unblock_buffer_flips (void);
  1142 static void redisplay_windows (Lisp_Object);
  1143 static void redisplay_window (Lisp_Object, bool);
  1144 static Lisp_Object redisplay_window_error (Lisp_Object);
  1145 static Lisp_Object redisplay_window_0 (Lisp_Object);
  1146 static Lisp_Object redisplay_window_1 (Lisp_Object);
  1147 static bool set_cursor_from_row (struct window *, struct glyph_row *,
  1148                                  struct glyph_matrix *, ptrdiff_t, ptrdiff_t,
  1149                                  int, int);
  1150 static bool cursor_row_fully_visible_p (struct window *, bool, bool, bool);
  1151 static bool update_menu_bar (struct frame *, bool, bool);
  1152 static bool try_window_reusing_current_matrix (struct window *);
  1153 static int try_window_id (struct window *);
  1154 static void maybe_produce_line_number (struct it *);
  1155 static bool should_produce_line_number (struct it *);
  1156 static bool display_line (struct it *, int);
  1157 static int display_mode_lines (struct window *);
  1158 static int display_mode_line (struct window *, enum face_id, Lisp_Object);
  1159 static int display_mode_element (struct it *, int, int, int, Lisp_Object,
  1160                                  Lisp_Object, bool);
  1161 static int store_mode_line_string (const char *, Lisp_Object, bool, int, int,
  1162                                    Lisp_Object);
  1163 static const char *decode_mode_spec (struct window *, int, int, Lisp_Object *);
  1164 static void display_menu_bar (struct window *);
  1165 static void display_tab_bar (struct window *);
  1166 static void update_tab_bar (struct frame *, bool);
  1167 static ptrdiff_t display_count_lines (ptrdiff_t, ptrdiff_t, ptrdiff_t,
  1168                                       ptrdiff_t *);
  1169 static void pint2str (register char *, register int, register ptrdiff_t);
  1170 
  1171 static int display_string (const char *, Lisp_Object, Lisp_Object,
  1172                            ptrdiff_t, ptrdiff_t, struct it *, int, int, int,
  1173                            int);
  1174 static void compute_line_metrics (struct it *);
  1175 static bool get_overlay_strings (struct it *, ptrdiff_t);
  1176 static bool get_overlay_strings_1 (struct it *, ptrdiff_t, bool);
  1177 static void next_overlay_string (struct it *);
  1178 static void reseat (struct it *, struct text_pos, bool);
  1179 static void reseat_1 (struct it *, struct text_pos, bool);
  1180 static bool next_element_from_display_vector (struct it *);
  1181 static bool next_element_from_string (struct it *);
  1182 static bool next_element_from_c_string (struct it *);
  1183 static bool next_element_from_buffer (struct it *);
  1184 static bool next_element_from_composition (struct it *);
  1185 static bool next_element_from_image (struct it *);
  1186 static bool next_element_from_stretch (struct it *);
  1187 static bool next_element_from_xwidget (struct it *);
  1188 static void load_overlay_strings (struct it *, ptrdiff_t);
  1189 static bool get_next_display_element (struct it *);
  1190 static enum move_it_result
  1191        move_it_in_display_line_to (struct it *, ptrdiff_t, int,
  1192                                    enum move_operation_enum);
  1193 static void get_visually_first_element (struct it *);
  1194 static void compute_stop_pos (struct it *);
  1195 static int face_before_or_after_it_pos (struct it *, bool);
  1196 static int handle_display_spec (struct it *, Lisp_Object, Lisp_Object,
  1197                                 Lisp_Object, struct text_pos *, ptrdiff_t, bool);
  1198 static int handle_single_display_spec (struct it *, Lisp_Object, Lisp_Object,
  1199                                        Lisp_Object, struct text_pos *,
  1200                                        ptrdiff_t, int, bool, bool);
  1201 static int underlying_face_id (const struct it *);
  1202 
  1203 #define face_before_it_pos(IT) face_before_or_after_it_pos (IT, true)
  1204 #define face_after_it_pos(IT)  face_before_or_after_it_pos (IT, false)
  1205 
  1206 #ifdef HAVE_WINDOW_SYSTEM
  1207 
  1208 static void update_tool_bar (struct frame *, bool);
  1209 static void gui_draw_bottom_divider (struct window *w);
  1210 static void notice_overwritten_cursor (struct window *,
  1211                                        enum glyph_row_area,
  1212                                        int, int, int, int);
  1213 static int  normal_char_height (struct font *, int);
  1214 static void normal_char_ascent_descent (struct font *, int, int *, int *);
  1215 
  1216 static void append_stretch_glyph (struct it *, Lisp_Object,
  1217                                   int, int, int);
  1218 
  1219 static Lisp_Object get_it_property (struct it *, Lisp_Object);
  1220 static Lisp_Object calc_line_height_property (struct it *, Lisp_Object,
  1221                                               struct font *, int, bool);
  1222 static int adjust_glyph_width_for_mouse_face (struct glyph *,
  1223                                               struct glyph_row *,
  1224                                               struct window *, struct face *,
  1225                                               struct face *);
  1226 static void get_cursor_offset_for_mouse_face (struct window *w,
  1227                                               struct glyph_row *row,
  1228                                               int *offset);
  1229 #endif /* HAVE_WINDOW_SYSTEM */
  1230 
  1231 static void produce_special_glyphs (struct it *, enum display_element_type);
  1232 static void pad_mode_line (struct it *, bool);
  1233 static void show_mouse_face (Mouse_HLInfo *, enum draw_glyphs_face);
  1234 static bool coords_in_mouse_face_p (struct window *, int, int);
  1235 static void reset_box_start_end_flags (struct it *);
  1236 
  1237 
  1238 
  1239 /***********************************************************************
  1240                       Window display dimensions
  1241  ***********************************************************************/
  1242 
  1243 /* Return the bottom boundary y-position for text lines in window W.
  1244    This is the first y position at which a line cannot start.
  1245    It is relative to the top of the window.
  1246 
  1247    This is the height of W minus the height of a mode line, if any.  */
  1248 
  1249 int
  1250 window_text_bottom_y (struct window *w)
  1251 {
  1252   int height = WINDOW_PIXEL_HEIGHT (w);
  1253 
  1254   height -= WINDOW_BOTTOM_DIVIDER_WIDTH (w);
  1255 
  1256   if (window_wants_mode_line (w))
  1257     height -= CURRENT_MODE_LINE_HEIGHT (w);
  1258 
  1259   height -= WINDOW_SCROLL_BAR_AREA_HEIGHT (w);
  1260 
  1261   return height;
  1262 }
  1263 
  1264 /* Return the pixel width of display area AREA of window W.
  1265    ANY_AREA means return the total width of W, not including
  1266    fringes to the left and right of the window.  */
  1267 
  1268 int
  1269 window_box_width (struct window *w, enum glyph_row_area area)
  1270 {
  1271   int width = w->pixel_width;
  1272 
  1273   if (!w->pseudo_window_p)
  1274     {
  1275       width -= WINDOW_SCROLL_BAR_AREA_WIDTH (w);
  1276       width -= WINDOW_RIGHT_DIVIDER_WIDTH (w);
  1277 
  1278       if (area == TEXT_AREA)
  1279         width -= (WINDOW_MARGINS_WIDTH (w)
  1280                    + WINDOW_FRINGES_WIDTH (w));
  1281       else if (area == LEFT_MARGIN_AREA)
  1282         width = WINDOW_LEFT_MARGIN_WIDTH (w);
  1283       else if (area == RIGHT_MARGIN_AREA)
  1284         width = WINDOW_RIGHT_MARGIN_WIDTH (w);
  1285     }
  1286 
  1287   /* With wide margins, fringes, etc. we might end up with a negative
  1288      width, correct that here.  */
  1289   return max (0, width);
  1290 }
  1291 
  1292 
  1293 /* Return the pixel height of the display area of window W, not
  1294    including mode lines of W, if any.  */
  1295 
  1296 int
  1297 window_box_height (struct window *w)
  1298 {
  1299   struct frame *f = XFRAME (w->frame);
  1300   int height = WINDOW_PIXEL_HEIGHT (w);
  1301 
  1302   eassert (height >= 0);
  1303 
  1304   height -= WINDOW_BOTTOM_DIVIDER_WIDTH (w);
  1305   height -= WINDOW_SCROLL_BAR_AREA_HEIGHT (w);
  1306 
  1307   /* Note: the code below that determines the mode-line/header-line/tab-line
  1308      height is essentially the same as that contained in the macro
  1309      CURRENT_{MODE,HEADER,TAB}_LINE_HEIGHT, except that it checks whether
  1310      the appropriate glyph row has its `mode_line_p' flag set, and if
  1311      it doesn't, uses estimate_mode_line_height instead.  */
  1312 
  1313   if (window_wants_mode_line (w))
  1314     {
  1315       if (w->mode_line_height >= 0)
  1316         height -= w->mode_line_height;
  1317       else
  1318         {
  1319           struct glyph_row *ml_row
  1320             = (w->current_matrix && w->current_matrix->rows
  1321                ? MATRIX_MODE_LINE_ROW (w->current_matrix)
  1322                : 0);
  1323           if (ml_row && ml_row->mode_line_p)
  1324             height -= ml_row->height;
  1325           else
  1326             height -= estimate_mode_line_height
  1327               (f, CURRENT_MODE_LINE_ACTIVE_FACE_ID (w));
  1328         }
  1329     }
  1330 
  1331   if (window_wants_tab_line (w))
  1332     {
  1333       if (w->tab_line_height >= 0)
  1334         height -= w->tab_line_height;
  1335       else
  1336         {
  1337           struct glyph_row *tl_row
  1338             = (w->current_matrix && w->current_matrix->rows
  1339                ? MATRIX_TAB_LINE_ROW (w->current_matrix)
  1340                : 0);
  1341           if (tl_row && tl_row->mode_line_p)
  1342             height -= tl_row->height;
  1343           else
  1344             height -= estimate_mode_line_height (f, TAB_LINE_FACE_ID);
  1345         }
  1346     }
  1347 
  1348   if (window_wants_header_line (w))
  1349     {
  1350       if (w->header_line_height >= 0)
  1351         height -= w->header_line_height;
  1352       else
  1353         {
  1354           struct glyph_row *hl_row
  1355             = (w->current_matrix && w->current_matrix->rows
  1356                ? MATRIX_HEADER_LINE_ROW (w->current_matrix)
  1357                : 0);
  1358           if (hl_row && hl_row->mode_line_p)
  1359             height -= hl_row->height;
  1360           else
  1361             height -= estimate_mode_line_height (f, HEADER_LINE_FACE_ID);
  1362         }
  1363     }
  1364 
  1365   /* With a very small font and a mode-line that's taller than
  1366      default, we might end up with a negative height.  */
  1367   return max (0, height);
  1368 }
  1369 
  1370 /* Return the window-relative coordinate of the left edge of display
  1371    area AREA of window W.  ANY_AREA means return the left edge of the
  1372    whole window, to the right of the left fringe of W.  */
  1373 
  1374 int
  1375 window_box_left_offset (struct window *w, enum glyph_row_area area)
  1376 {
  1377   int x;
  1378 
  1379   if (w->pseudo_window_p)
  1380     return 0;
  1381 
  1382   x = WINDOW_LEFT_SCROLL_BAR_AREA_WIDTH (w);
  1383 
  1384   if (area == TEXT_AREA)
  1385     x += (WINDOW_LEFT_FRINGE_WIDTH (w)
  1386           + window_box_width (w, LEFT_MARGIN_AREA));
  1387   else if (area == RIGHT_MARGIN_AREA)
  1388     x += (WINDOW_LEFT_FRINGE_WIDTH (w)
  1389           + window_box_width (w, LEFT_MARGIN_AREA)
  1390           + window_box_width (w, TEXT_AREA)
  1391           + (WINDOW_HAS_FRINGES_OUTSIDE_MARGINS (w)
  1392              ? 0
  1393              : WINDOW_RIGHT_FRINGE_WIDTH (w)));
  1394   else if (area == LEFT_MARGIN_AREA
  1395            && WINDOW_HAS_FRINGES_OUTSIDE_MARGINS (w))
  1396     x += WINDOW_LEFT_FRINGE_WIDTH (w);
  1397 
  1398   /* Don't return more than the window's pixel width.  */
  1399   return min (x, w->pixel_width);
  1400 }
  1401 
  1402 
  1403 /* Return the window-relative coordinate of the right edge of display
  1404    area AREA of window W.  ANY_AREA means return the right edge of the
  1405    whole window, to the left of the right fringe of W.  */
  1406 
  1407 static int
  1408 window_box_right_offset (struct window *w, enum glyph_row_area area)
  1409 {
  1410   /* Don't return more than the window's pixel width.  */
  1411   return min (window_box_left_offset (w, area) + window_box_width (w, area),
  1412               w->pixel_width);
  1413 }
  1414 
  1415 /* Return the frame-relative coordinate of the left edge of display
  1416    area AREA of window W.  ANY_AREA means return the left edge of the
  1417    whole window, to the right of the left fringe of W.  */
  1418 
  1419 int
  1420 window_box_left (struct window *w, enum glyph_row_area area)
  1421 {
  1422   struct frame *f = XFRAME (w->frame);
  1423   int x;
  1424 
  1425   if (w->pseudo_window_p)
  1426     return FRAME_INTERNAL_BORDER_WIDTH (f);
  1427 
  1428   x = (WINDOW_LEFT_EDGE_X (w)
  1429        + window_box_left_offset (w, area));
  1430 
  1431   return x;
  1432 }
  1433 
  1434 
  1435 /* Return the frame-relative coordinate of the right edge of display
  1436    area AREA of window W.  ANY_AREA means return the right edge of the
  1437    whole window, to the left of the right fringe of W.  */
  1438 
  1439 int
  1440 window_box_right (struct window *w, enum glyph_row_area area)
  1441 {
  1442   return window_box_left (w, area) + window_box_width (w, area);
  1443 }
  1444 
  1445 /* Get the bounding box of the display area AREA of window W, without
  1446    mode lines, in frame-relative coordinates.  ANY_AREA means the
  1447    whole window, not including the left and right fringes of
  1448    the window.  Return in *BOX_X and *BOX_Y the frame-relative pixel
  1449    coordinates of the upper-left corner of the box.  Return in
  1450    *BOX_WIDTH, and *BOX_HEIGHT the pixel width and height of the box.  */
  1451 
  1452 void
  1453 window_box (struct window *w, enum glyph_row_area area, int *box_x,
  1454             int *box_y, int *box_width, int *box_height)
  1455 {
  1456   if (box_width)
  1457     *box_width = window_box_width (w, area);
  1458   if (box_height)
  1459     *box_height = window_box_height (w);
  1460   if (box_x)
  1461     *box_x = window_box_left (w, area);
  1462   if (box_y)
  1463     {
  1464       *box_y = WINDOW_TOP_EDGE_Y (w);
  1465       if (window_wants_tab_line (w))
  1466         *box_y += CURRENT_TAB_LINE_HEIGHT (w);
  1467       if (window_wants_header_line (w))
  1468         *box_y += CURRENT_HEADER_LINE_HEIGHT (w);
  1469     }
  1470 }
  1471 
  1472 #ifdef HAVE_WINDOW_SYSTEM
  1473 
  1474 /* Get the bounding box of the display area AREA of window W, without
  1475    mode lines and both fringes of the window.  Return in *TOP_LEFT_X
  1476    and TOP_LEFT_Y the frame-relative pixel coordinates of the
  1477    upper-left corner of the box.  Return in *BOTTOM_RIGHT_X, and
  1478    *BOTTOM_RIGHT_Y the coordinates of the bottom-right corner of the
  1479    box.  */
  1480 
  1481 static void
  1482 window_box_edges (struct window *w, int *top_left_x, int *top_left_y,
  1483                   int *bottom_right_x, int *bottom_right_y)
  1484 {
  1485   window_box (w, ANY_AREA, top_left_x, top_left_y,
  1486               bottom_right_x, bottom_right_y);
  1487   *bottom_right_x += *top_left_x;
  1488   *bottom_right_y += *top_left_y;
  1489 }
  1490 
  1491 #endif /* HAVE_WINDOW_SYSTEM */
  1492 
  1493 /***********************************************************************
  1494                               Utilities
  1495  ***********************************************************************/
  1496 
  1497 /* Return the bottom y-position of the line the iterator IT is in.
  1498    This can modify IT's settings.  */
  1499 
  1500 int
  1501 line_bottom_y (struct it *it)
  1502 {
  1503   int line_height = it->max_ascent + it->max_descent;
  1504   int line_top_y = it->current_y;
  1505 
  1506   if (line_height == 0)
  1507     {
  1508       if (last_height)
  1509         line_height = last_height;
  1510       else if (IT_CHARPOS (*it) < ZV)
  1511         {
  1512           move_it_by_lines (it, 1);
  1513           line_height = (it->max_ascent || it->max_descent
  1514                          ? it->max_ascent + it->max_descent
  1515                          : last_height);
  1516         }
  1517       else
  1518         {
  1519           struct glyph_row *row = it->glyph_row;
  1520 
  1521           /* Use the default character height.  */
  1522           it->glyph_row = NULL;
  1523           it->what = IT_CHARACTER;
  1524           it->c = ' ';
  1525           it->len = 1;
  1526           PRODUCE_GLYPHS (it);
  1527           line_height = it->ascent + it->descent;
  1528           it->glyph_row = row;
  1529         }
  1530     }
  1531 
  1532   return line_top_y + line_height;
  1533 }
  1534 
  1535 DEFUN ("line-pixel-height", Fline_pixel_height,
  1536        Sline_pixel_height, 0, 0, 0,
  1537        doc: /* Return height in pixels of text line in the selected window.
  1538 
  1539 Value is the height in pixels of the line at point.  */)
  1540   (void)
  1541 {
  1542   struct it it;
  1543   struct text_pos pt;
  1544   struct window *w = XWINDOW (selected_window);
  1545   struct buffer *old_buffer = NULL;
  1546   Lisp_Object result;
  1547 
  1548   if (XBUFFER (w->contents) != current_buffer)
  1549     {
  1550       old_buffer = current_buffer;
  1551       set_buffer_internal_1 (XBUFFER (w->contents));
  1552     }
  1553   SET_TEXT_POS (pt, PT, PT_BYTE);
  1554   void *itdata = bidi_shelve_cache ();
  1555   start_display (&it, w, pt);
  1556   /* Start from the beginning of the screen line, to make sure we
  1557      traverse all of its display elements, and thus capture the
  1558      correct metrics.  */
  1559   move_it_by_lines (&it, 0);
  1560   it.vpos = it.current_y = 0;
  1561   last_height = 0;
  1562   result = make_fixnum (line_bottom_y (&it));
  1563   if (old_buffer)
  1564     set_buffer_internal_1 (old_buffer);
  1565 
  1566   bidi_unshelve_cache (itdata, false);
  1567   return result;
  1568 }
  1569 
  1570 /* Return the default pixel height of text lines in window W.  The
  1571    value is the canonical height of the W frame's default font, plus
  1572    any extra space required by the line-spacing variable or frame
  1573    parameter.
  1574 
  1575    Implementation note: this ignores any line-spacing text properties
  1576    put on the newline characters.  This is because those properties
  1577    only affect the _screen_ line ending in the newline (i.e., in a
  1578    continued line, only the last screen line will be affected), which
  1579    means only a small number of lines in a buffer can ever use this
  1580    feature.  Since this function is used to compute the default pixel
  1581    equivalent of text lines in a window, we can safely ignore those
  1582    few lines.  For the same reasons, we ignore the line-height
  1583    properties.  */
  1584 int
  1585 default_line_pixel_height (struct window *w)
  1586 {
  1587   struct frame *f = WINDOW_XFRAME (w);
  1588   int height = FRAME_LINE_HEIGHT (f);
  1589 
  1590   if (!FRAME_INITIAL_P (f) && BUFFERP (w->contents))
  1591     {
  1592       struct buffer *b = XBUFFER (w->contents);
  1593       Lisp_Object val = BVAR (b, extra_line_spacing);
  1594 
  1595       if (NILP (val))
  1596         val = BVAR (&buffer_defaults, extra_line_spacing);
  1597       if (!NILP (val))
  1598         {
  1599           if (RANGED_FIXNUMP (0, val, INT_MAX))
  1600             height += XFIXNAT (val);
  1601           else if (FLOATP (val))
  1602             {
  1603               int addon = XFLOAT_DATA (val) * height + 0.5;
  1604 
  1605               if (addon >= 0)
  1606                 height += addon;
  1607             }
  1608         }
  1609       else
  1610         height += f->extra_line_spacing;
  1611     }
  1612 
  1613   return height;
  1614 }
  1615 
  1616 /* Subroutine of pos_visible_p below.  Extracts a display string, if
  1617    any, from the display spec given as its argument.  */
  1618 static Lisp_Object
  1619 string_from_display_spec (Lisp_Object spec)
  1620 {
  1621   if (VECTORP (spec))
  1622     {
  1623       for (ptrdiff_t i = 0; i < ASIZE (spec); i++)
  1624         if (STRINGP (AREF (spec, i)))
  1625           return AREF (spec, i);
  1626     }
  1627   else
  1628     {
  1629       for (; CONSP (spec); spec = XCDR (spec))
  1630         if (STRINGP (XCAR (spec)))
  1631           return XCAR (spec);
  1632     }
  1633   return spec;
  1634 }
  1635 
  1636 
  1637 /* Limit insanely large values of W->hscroll on frame F to the largest
  1638    value that will still prevent first_visible_x and last_visible_x of
  1639    'struct it' from overflowing an int.  */
  1640 static int
  1641 window_hscroll_limited (struct window *w, struct frame *f)
  1642 {
  1643   ptrdiff_t window_hscroll = w->hscroll;
  1644   int window_text_width = window_box_width (w, TEXT_AREA);
  1645   int colwidth = FRAME_COLUMN_WIDTH (f);
  1646 
  1647   if (window_hscroll > (INT_MAX - window_text_width) / colwidth - 1)
  1648     window_hscroll = (INT_MAX - window_text_width) / colwidth - 1;
  1649 
  1650   return window_hscroll;
  1651 }
  1652 
  1653 /* Reset the box-face start and end flags in the iterator.  This is
  1654    called after producing glyphs, such that we reset these flags only
  1655    after producing a glyph with the flag set.  */
  1656 
  1657 static void
  1658 reset_box_start_end_flags (struct it *it)
  1659 {
  1660   /* Don't reset if we've drawn the glyph in the display margins --
  1661      those don't count as "produced glyphs".  */
  1662   if (it->area == TEXT_AREA
  1663       /* Don't reset if we displayed a fringe bitmap.  */
  1664       && !(it->what == IT_IMAGE && it->image_id < 0))
  1665     {
  1666       /* Don't reset if the face is not a box face: that might mean we
  1667          are iterating some overlay or display string, and the first
  1668          character to have the box face is yet to be seen, when we pop
  1669          the iterator stack. */
  1670       if (it->face_box_p)
  1671         it->start_of_box_run_p = false;
  1672       it->end_of_box_run_p = false;
  1673     }
  1674 }
  1675 
  1676 /* Return true if position CHARPOS is visible in window W.
  1677    CHARPOS < 0 means return info about WINDOW_END position.
  1678    If visible, set *X and *Y to pixel coordinates of top left corner.
  1679    Set *RTOP and *RBOT to pixel height of an invisible area of glyph at POS.
  1680    Set *ROWH and *VPOS to row's visible height and VPOS (row number).  */
  1681 
  1682 bool
  1683 pos_visible_p (struct window *w, ptrdiff_t charpos, int *x, int *y,
  1684                int *rtop, int *rbot, int *rowh, int *vpos)
  1685 {
  1686   struct it it;
  1687   void *itdata = bidi_shelve_cache ();
  1688   struct text_pos top;
  1689   bool visible_p = false;
  1690   struct buffer *old_buffer = NULL;
  1691   bool r2l = false;
  1692 
  1693   if (FRAME_INITIAL_P (XFRAME (WINDOW_FRAME (w))))
  1694     return visible_p;
  1695 
  1696   if (XBUFFER (w->contents) != current_buffer)
  1697     {
  1698       old_buffer = current_buffer;
  1699       set_buffer_internal_1 (XBUFFER (w->contents));
  1700     }
  1701 
  1702   SET_TEXT_POS_FROM_MARKER (top, w->start);
  1703   /* Scrolling a minibuffer window via scroll bar when the echo area
  1704      shows long text sometimes resets the minibuffer contents behind
  1705      our backs.  Also, someone might narrow-to-region and immediately
  1706      call a scroll function.  */
  1707   if (CHARPOS (top) > ZV || CHARPOS (top) < BEGV)
  1708     SET_TEXT_POS (top, BEGV, BEGV_BYTE);
  1709 
  1710   /* If the top of the window is after CHARPOS, the latter is surely
  1711      not visible.  */
  1712   if (charpos >= 0 && CHARPOS (top) > charpos)
  1713     return visible_p;
  1714 
  1715   /* Some Lisp hook could call us in the middle of redisplaying this
  1716      very window.  If, by some bad luck, we are retrying redisplay
  1717      because we found that the mode-line height and/or tab/header-line
  1718      height needs to be updated, the assignment of mode_line_height
  1719      and header_line_height below could disrupt that, due to the
  1720      selected/nonselected window dance during mode-line display, and
  1721      we could infloop.  Avoid that.  */
  1722   int prev_mode_line_height = w->mode_line_height;
  1723   int prev_header_line_height = w->header_line_height;
  1724   int prev_tab_line_height = w->tab_line_height;
  1725   /* Compute exact mode line heights.  */
  1726   if (window_wants_mode_line (w))
  1727     {
  1728       Lisp_Object window_mode_line_format
  1729         = window_parameter (w, Qmode_line_format);
  1730 
  1731       w->mode_line_height
  1732         = display_mode_line (w, CURRENT_MODE_LINE_ACTIVE_FACE_ID (w),
  1733                              NILP (window_mode_line_format)
  1734                              ? BVAR (current_buffer, mode_line_format)
  1735                              : window_mode_line_format);
  1736     }
  1737 
  1738   if (window_wants_tab_line (w))
  1739     {
  1740       Lisp_Object window_tab_line_format
  1741         = window_parameter (w, Qtab_line_format);
  1742 
  1743       w->tab_line_height
  1744         = display_mode_line (w, TAB_LINE_FACE_ID,
  1745                              NILP (window_tab_line_format)
  1746                              ? BVAR (current_buffer, tab_line_format)
  1747                              : window_tab_line_format);
  1748     }
  1749 
  1750   if (window_wants_header_line (w))
  1751     {
  1752       Lisp_Object window_header_line_format
  1753         = window_parameter (w, Qheader_line_format);
  1754 
  1755       w->header_line_height
  1756         = display_mode_line (w, HEADER_LINE_FACE_ID,
  1757                              NILP (window_header_line_format)
  1758                              ? BVAR (current_buffer, header_line_format)
  1759                              : window_header_line_format);
  1760     }
  1761 
  1762   start_display (&it, w, top);
  1763   move_it_to (&it, charpos, -1, it.last_visible_y - 1, -1,
  1764               (charpos >= 0 ? MOVE_TO_POS : 0) | MOVE_TO_Y);
  1765 
  1766   /* Adjust for line numbers, if CHARPOS is at or beyond first_visible_x,
  1767      but we didn't yet produce the line-number glyphs.  */
  1768   if (!NILP (Vdisplay_line_numbers)
  1769       && it.current_x >= it.first_visible_x
  1770       && IT_CHARPOS (it) == charpos
  1771       && !it.line_number_produced_p)
  1772     {
  1773       /* If the pixel width of line numbers was not yet known, compute
  1774          it now.  This usually happens in the first display line of a
  1775          window.  */
  1776       if (!it.lnum_pixel_width)
  1777         {
  1778           struct it it2;
  1779           void *it2data = NULL;
  1780 
  1781           SAVE_IT (it2, it, it2data);
  1782           move_it_by_lines (&it, 1);
  1783           it2.lnum_pixel_width = it.lnum_pixel_width;
  1784           RESTORE_IT (&it, &it2, it2data);
  1785         }
  1786       it.current_x += it.lnum_pixel_width;
  1787     }
  1788 
  1789   if (charpos >= 0
  1790       && (((!it.bidi_p || it.bidi_it.scan_dir != -1)
  1791            && IT_CHARPOS (it) >= charpos)
  1792           /* When scanning backwards under bidi iteration, move_it_to
  1793              stops at or _before_ CHARPOS, because it stops at or to
  1794              the _right_ of the character at CHARPOS.  */
  1795           || (it.bidi_p && it.bidi_it.scan_dir == -1
  1796               && IT_CHARPOS (it) <= charpos)))
  1797     {
  1798       /* We have reached CHARPOS, or passed it.  How the call to
  1799          move_it_to can overshoot: (i) If CHARPOS is on invisible text
  1800          or covered by a display property, move_it_to stops at the end
  1801          of the invisible text, to the right of CHARPOS.  (ii) If
  1802          CHARPOS is in a display vector, move_it_to stops on its last
  1803          glyph.  */
  1804       int top_x = it.current_x;
  1805       int top_y = it.current_y;
  1806       int window_top_y = WINDOW_TAB_LINE_HEIGHT (w) + WINDOW_HEADER_LINE_HEIGHT (w);
  1807       int bottom_y;
  1808       struct it save_it;
  1809       void *save_it_data = NULL;
  1810 
  1811       /* Calling line_bottom_y may change it.method, it.position, etc.  */
  1812       SAVE_IT (save_it, it, save_it_data);
  1813       last_height = 0;
  1814       bottom_y = line_bottom_y (&it);
  1815       if (top_y < window_top_y)
  1816         visible_p = bottom_y > window_top_y;
  1817       else if (top_y < it.last_visible_y)
  1818         visible_p = true;
  1819       if (bottom_y >= it.last_visible_y
  1820           && it.bidi_p && it.bidi_it.scan_dir == -1
  1821           && IT_CHARPOS (it) < charpos)
  1822         {
  1823           /* When the last line of the window is scanned backwards
  1824              under bidi iteration, we could be duped into thinking
  1825              that we have passed CHARPOS, when in fact move_it_to
  1826              simply stopped short of CHARPOS because it reached
  1827              last_visible_y.  To see if that's what happened, we call
  1828              move_it_to again with a slightly larger vertical limit,
  1829              and see if it actually moved vertically; if it did, we
  1830              didn't really reach CHARPOS, which is beyond window end.  */
  1831           /* Why 10? because we don't know how many canonical lines
  1832              will the height of the next line(s) be.  So we guess.  */
  1833           int ten_more_lines = 10 * default_line_pixel_height (w);
  1834 
  1835           move_it_to (&it, charpos, -1, bottom_y + ten_more_lines, -1,
  1836                       MOVE_TO_POS | MOVE_TO_Y);
  1837           if (it.current_y > top_y)
  1838             visible_p = false;
  1839 
  1840         }
  1841       RESTORE_IT (&it, &save_it, save_it_data);
  1842       if (visible_p)
  1843         {
  1844           if (it.method == GET_FROM_DISPLAY_VECTOR)
  1845             {
  1846               /* We stopped on the last glyph of a display vector.
  1847                  Try and recompute.  Hack alert!  */
  1848               if (charpos < 2 || top.charpos >= charpos)
  1849                 top_x = it.glyph_row->x;
  1850               else
  1851                 {
  1852                   struct it it2, it2_prev;
  1853                   /* The idea is to get to the previous buffer
  1854                      position, consume the character there, and use
  1855                      the pixel coordinates we get after that.  But if
  1856                      the previous buffer position is also displayed
  1857                      from a display vector, we need to consume all of
  1858                      the glyphs from that display vector.  */
  1859                   start_display (&it2, w, top);
  1860                   it2.glyph_row = NULL;
  1861                   move_it_to (&it2, charpos - 1, -1, -1, -1, MOVE_TO_POS);
  1862                   /* If we didn't get to CHARPOS - 1, there's some
  1863                      replacing display property at that position, and
  1864                      we stopped after it.  That is exactly the place
  1865                      whose coordinates we want.  */
  1866                   if (IT_CHARPOS (it2) != charpos - 1)
  1867                     it2_prev = it2;
  1868                   else
  1869                     {
  1870                       /* Iterate until we get out of the display
  1871                          vector that displays the character at
  1872                          CHARPOS - 1.  */
  1873                       do {
  1874                         get_next_display_element (&it2);
  1875                         PRODUCE_GLYPHS (&it2);
  1876                         it2_prev = it2;
  1877                         set_iterator_to_next (&it2, true);
  1878                       } while (it2.method == GET_FROM_DISPLAY_VECTOR
  1879                                && IT_CHARPOS (it2) < charpos);
  1880                     }
  1881                   if (ITERATOR_AT_END_OF_LINE_P (&it2_prev)
  1882                       || it2_prev.current_x > it2_prev.last_visible_x)
  1883                     top_x = it.glyph_row->x;
  1884                   else
  1885                     {
  1886                       top_x = it2_prev.current_x;
  1887                       top_y = it2_prev.current_y;
  1888                     }
  1889                 }
  1890             }
  1891           else if (IT_CHARPOS (it) != charpos)
  1892             {
  1893               Lisp_Object cpos = make_fixnum (charpos);
  1894               Lisp_Object spec = Fget_char_property (cpos, Qdisplay, Qnil);
  1895               Lisp_Object string = string_from_display_spec (spec);
  1896               struct text_pos tpos;
  1897               bool newline_in_string
  1898                 = (STRINGP (string)
  1899                    && memchr (SDATA (string), '\n', SBYTES (string)));
  1900 
  1901               SET_TEXT_POS (tpos, charpos, CHAR_TO_BYTE (charpos));
  1902               bool replacing_spec_p
  1903                 = (!NILP (spec)
  1904                    && handle_display_spec (NULL, spec, Qnil, Qnil, &tpos,
  1905                                            charpos, FRAME_WINDOW_P (it.f)));
  1906               /* The tricky code below is needed because there's a
  1907                  discrepancy between move_it_to and how we set cursor
  1908                  when PT is at the beginning of a portion of text
  1909                  covered by a display property or an overlay with a
  1910                  display property, or the display line ends in a
  1911                  newline from a display string.  move_it_to will stop
  1912                  _after_ such display strings, whereas
  1913                  set_cursor_from_row conspires with cursor_row_p to
  1914                  place the cursor on the first glyph produced from the
  1915                  display string.  */
  1916 
  1917               /* We have overshoot PT because it is covered by a
  1918                  display property that replaces the text it covers.
  1919                  If the string includes embedded newlines, we are also
  1920                  in the wrong display line.  Backtrack to the correct
  1921                  line, where the display property begins.  */
  1922               if (replacing_spec_p)
  1923                 {
  1924                   Lisp_Object startpos, endpos;
  1925                   EMACS_INT start, end;
  1926                   struct it it3;
  1927 
  1928                   /* Find the first and the last buffer positions
  1929                      covered by the display string.  */
  1930                   endpos =
  1931                     Fnext_single_char_property_change (cpos, Qdisplay,
  1932                                                        Qnil, Qnil);
  1933                   startpos =
  1934                     Fprevious_single_char_property_change (endpos, Qdisplay,
  1935                                                            Qnil, Qnil);
  1936                   start = XFIXNAT (startpos);
  1937                   end = XFIXNAT (endpos);
  1938                   /* Move to the last buffer position before the
  1939                      display property.  */
  1940                   start_display (&it3, w, top);
  1941                   if (start > CHARPOS (top))
  1942                     move_it_to (&it3, start - 1, -1, -1, -1, MOVE_TO_POS);
  1943                   /* Move forward one more line if the position before
  1944                      the display string is a newline or if it is the
  1945                      rightmost character on a line that is
  1946                      continued or word-wrapped.  */
  1947                   if (it3.method == GET_FROM_BUFFER
  1948                       && (it3.c == '\n'
  1949                           || FETCH_BYTE (IT_BYTEPOS (it3)) == '\n'))
  1950                     move_it_by_lines (&it3, 1);
  1951                   else if (move_it_in_display_line_to (&it3, -1,
  1952                                                        it3.current_x
  1953                                                        + it3.pixel_width,
  1954                                                        MOVE_TO_X)
  1955                            == MOVE_LINE_CONTINUED)
  1956                     {
  1957                       move_it_by_lines (&it3, 1);
  1958                       /* When we are under word-wrap, the #$@%!
  1959                          move_it_by_lines moves 2 lines, so we need to
  1960                          fix that up.  */
  1961                       if (it3.line_wrap == WORD_WRAP)
  1962                         move_it_by_lines (&it3, -1);
  1963                     }
  1964 
  1965                   /* Record the vertical coordinate of the display
  1966                      line where we wound up.  */
  1967                   top_y = it3.current_y;
  1968                   if (it3.bidi_p)
  1969                     {
  1970                       /* When characters are reordered for display,
  1971                          the character displayed to the left of the
  1972                          display string could be _after_ the display
  1973                          property in the logical order.  Use the
  1974                          smallest vertical position of these two.  */
  1975                       start_display (&it3, w, top);
  1976                       move_it_to (&it3, end + 1, -1, -1, -1, MOVE_TO_POS);
  1977                       if (it3.current_y < top_y)
  1978                         top_y = it3.current_y;
  1979                     }
  1980                   /* Move from the top of the window to the beginning
  1981                      of the display line where the display string
  1982                      begins.  */
  1983                   start_display (&it3, w, top);
  1984                   it3.glyph_row = NULL;
  1985                   move_it_to (&it3, -1, 0, top_y, -1, MOVE_TO_X | MOVE_TO_Y);
  1986                   /* If it3_moved stays false after the 'while' loop
  1987                      below, that means we already were at a newline
  1988                      before the loop (e.g., the display string begins
  1989                      with a newline), so we don't need to return to
  1990                      the last position before the display string,
  1991                      because PRODUCE_GLYPHS will not produce anything
  1992                      for a newline.  */
  1993                   bool it3_moved = false;
  1994                   int top_x_before_string = it3.current_x;
  1995                   /* Finally, advance the iterator until we hit the
  1996                      first display element whose character position is
  1997                      at or beyond CHARPOS, or until the first newline
  1998                      from the display string, which signals the end of
  1999                      the display line.  */
  2000                   while (get_next_display_element (&it3))
  2001                     {
  2002                       if (!EQ (it3.object, string))
  2003                         top_x_before_string = it3.current_x;
  2004                       PRODUCE_GLYPHS (&it3);
  2005                       if ((it3.bidi_it.scan_dir == 1
  2006                            && IT_CHARPOS (it3) >= charpos)
  2007                           || (it3.bidi_it.scan_dir == -1
  2008                               && IT_CHARPOS (it3) <= charpos)
  2009                           || ITERATOR_AT_END_OF_LINE_P (&it3))
  2010                         break;
  2011                       it3_moved = true;
  2012                       set_iterator_to_next (&it3, false);
  2013                     }
  2014                   top_x = it3.current_x - it3.pixel_width;
  2015                   /* Account for line-number display, if IT3 still
  2016                      didn't.  This can happen if START - 1 is the
  2017                      first or the last character on its display line.  */
  2018                   if (!it3.line_number_produced_p)
  2019                     {
  2020                       if (it3.lnum_pixel_width > 0)
  2021                         {
  2022                           top_x += it3.lnum_pixel_width;
  2023                           top_x_before_string += it3.lnum_pixel_width;
  2024                         }
  2025                       else if (it.line_number_produced_p)
  2026                         {
  2027                           top_x += it.lnum_pixel_width;
  2028                           top_x_before_string += it3.lnum_pixel_width;
  2029                         }
  2030                     }
  2031                   /* Normally, we would exit the above loop because we
  2032                      found the display element whose character
  2033                      position is CHARPOS.  For the contingency that we
  2034                      didn't, and stopped at the first newline from the
  2035                      display string, reset top_x to the coordinate of
  2036                      the rightmost glyph not from the string.  */
  2037                   if (it3_moved
  2038                       && newline_in_string
  2039                       && IT_CHARPOS (it3) != charpos && EQ (it3.object, string))
  2040                     top_x = top_x_before_string;
  2041                 }
  2042             }
  2043 
  2044           *x = top_x;
  2045           /* The condition below is a heuristic fix for the situation
  2046              where move_it_to stops just after finishing the display
  2047              of a fringe bitmap, which resets it.ascent to zero, and
  2048              thus causes Y to be offset by it.max_ascent.  */
  2049           if (it.ascent == 0 && it.what == IT_IMAGE
  2050               && it.method != GET_FROM_IMAGE
  2051               && it.image_id < 0
  2052               && it.max_ascent > 0)
  2053             *y = max (top_y, window_top_y);
  2054           else
  2055             *y = max (top_y + max (0, it.max_ascent - it.ascent), window_top_y);
  2056           *rtop = max (0, window_top_y - top_y);
  2057           *rbot = max (0, bottom_y - it.last_visible_y);
  2058           *rowh = max (0, (min (bottom_y, it.last_visible_y)
  2059                            - max (top_y, window_top_y)));
  2060           *vpos = it.vpos;
  2061           if (it.bidi_it.paragraph_dir == R2L)
  2062             r2l = true;
  2063         }
  2064     }
  2065   else
  2066     {
  2067       /* Either we were asked to provide info about WINDOW_END, or
  2068          CHARPOS is in the partially visible glyph row at end of
  2069          window.  */
  2070       struct it it2;
  2071       void *it2data = NULL;
  2072 
  2073       SAVE_IT (it2, it, it2data);
  2074       if (IT_CHARPOS (it) < ZV && FETCH_BYTE (IT_BYTEPOS (it)) != '\n')
  2075         move_it_by_lines (&it, 1);
  2076       if (charpos < IT_CHARPOS (it)
  2077           || (it.what == IT_EOB && charpos == IT_CHARPOS (it)))
  2078         {
  2079           visible_p = true;
  2080           RESTORE_IT (&it2, &it2, it2data);
  2081           move_it_to (&it2, charpos, -1, -1, -1, MOVE_TO_POS);
  2082           *x = it2.current_x;
  2083           if (it2.ascent == 0 && it2.what == IT_IMAGE
  2084               && it2.method != GET_FROM_IMAGE
  2085               && it2.image_id < 0
  2086               && it2.max_ascent > 0)
  2087             *y = it2.current_y;
  2088           else
  2089             *y = it2.current_y + it2.max_ascent - it2.ascent;
  2090           *rtop = max (0, -it2.current_y);
  2091           *rbot = max (0, ((it2.current_y + it2.max_ascent + it2.max_descent)
  2092                            - it.last_visible_y));
  2093           *rowh = max (0, (min (it2.current_y + it2.max_ascent + it2.max_descent,
  2094                                 it.last_visible_y)
  2095                            - max (max (it2.current_y,
  2096                                        WINDOW_TAB_LINE_HEIGHT (w)),
  2097                                   WINDOW_HEADER_LINE_HEIGHT (w))));
  2098           *vpos = it2.vpos;
  2099           if (it2.bidi_it.paragraph_dir == R2L)
  2100             r2l = true;
  2101         }
  2102       else
  2103         bidi_unshelve_cache (it2data, true);
  2104     }
  2105   bidi_unshelve_cache (itdata, false);
  2106 
  2107   if (old_buffer)
  2108     set_buffer_internal_1 (old_buffer);
  2109 
  2110   if (visible_p)
  2111     {
  2112       if (w->hscroll > 0)
  2113         *x -=
  2114           window_hscroll_limited (w, WINDOW_XFRAME (w))
  2115           * WINDOW_FRAME_COLUMN_WIDTH (w);
  2116       /* For lines in an R2L paragraph, we need to mirror the X pixel
  2117          coordinate wrt the text area.  For the reasons, see the
  2118          commentary in buffer_posn_from_coords and the explanation of
  2119          the geometry used by the move_it_* functions at the end of
  2120          the large commentary near the beginning of this file.  */
  2121       if (r2l)
  2122         *x = window_box_width (w, TEXT_AREA) - *x - 1;
  2123     }
  2124 
  2125 #if false
  2126   /* Debugging code.  */
  2127   if (visible_p)
  2128     fprintf (stderr, "+pv pt=%d vs=%d --> x=%d y=%d rt=%d rb=%d rh=%d vp=%d\n",
  2129              charpos, w->vscroll, *x, *y, *rtop, *rbot, *rowh, *vpos);
  2130   else
  2131     fprintf (stderr, "-pv pt=%d vs=%d\n", charpos, w->vscroll);
  2132 #endif
  2133 
  2134   /* Restore potentially overwritten values.  */
  2135   w->mode_line_height = prev_mode_line_height;
  2136   w->header_line_height = prev_header_line_height;
  2137   w->tab_line_height = prev_tab_line_height;
  2138 
  2139   return visible_p;
  2140 }
  2141 
  2142 
  2143 /* Return the next character from STR.  Return in *LEN the length of
  2144    the character.  This is like string_char_and_length but never
  2145    returns an invalid character.  If we find one, we return a `?', but
  2146    with the length of the invalid character.  */
  2147 
  2148 static int
  2149 check_char_and_length (const unsigned char *str, int *len)
  2150 {
  2151   int c = string_char_and_length (str, len);
  2152   if (!CHAR_VALID_P (c))
  2153     /* We may not change the length here because other places in Emacs
  2154        don't use this function, i.e. they silently accept invalid
  2155        characters.  */
  2156     c = '?';
  2157 
  2158   return c;
  2159 }
  2160 
  2161 
  2162 
  2163 /* Given a position POS containing a valid character and byte position
  2164    in STRING, return the position NCHARS ahead (NCHARS >= 0).  */
  2165 
  2166 static struct text_pos
  2167 string_pos_nchars_ahead (struct text_pos pos, Lisp_Object string, ptrdiff_t nchars)
  2168 {
  2169   eassert (STRINGP (string) && nchars >= 0);
  2170 
  2171   if (STRING_MULTIBYTE (string))
  2172     {
  2173       const unsigned char *p = SDATA (string) + BYTEPOS (pos);
  2174 
  2175       while (nchars--)
  2176         {
  2177           int len = BYTES_BY_CHAR_HEAD (*p);
  2178           p += len;
  2179           CHARPOS (pos) += 1;
  2180           BYTEPOS (pos) += len;
  2181         }
  2182     }
  2183   else
  2184     SET_TEXT_POS (pos, CHARPOS (pos) + nchars, BYTEPOS (pos) + nchars);
  2185 
  2186   return pos;
  2187 }
  2188 
  2189 
  2190 /* Value is the text position, i.e. character and byte position,
  2191    for character position CHARPOS in STRING.  */
  2192 
  2193 static struct text_pos
  2194 string_pos (ptrdiff_t charpos, Lisp_Object string)
  2195 {
  2196   struct text_pos pos;
  2197   eassert (STRINGP (string));
  2198   eassert (charpos >= 0);
  2199   SET_TEXT_POS (pos, charpos, string_char_to_byte (string, charpos));
  2200   return pos;
  2201 }
  2202 
  2203 
  2204 /* Value is a text position, i.e. character and byte position, for
  2205    character position CHARPOS in C string S.  MULTIBYTE_P
  2206    means recognize multibyte characters.  */
  2207 
  2208 static struct text_pos
  2209 c_string_pos (ptrdiff_t charpos, const char *s, bool multibyte_p)
  2210 {
  2211   struct text_pos pos;
  2212 
  2213   eassert (s != NULL);
  2214   eassert (charpos >= 0);
  2215 
  2216   if (multibyte_p)
  2217     {
  2218       SET_TEXT_POS (pos, 0, 0);
  2219       while (charpos--)
  2220         {
  2221           int len = BYTES_BY_CHAR_HEAD (*s);
  2222           s += len;
  2223           CHARPOS (pos) += 1;
  2224           BYTEPOS (pos) += len;
  2225         }
  2226     }
  2227   else
  2228     SET_TEXT_POS (pos, charpos, charpos);
  2229 
  2230   return pos;
  2231 }
  2232 
  2233 
  2234 /* Value is the number of characters in C string S.  MULTIBYTE_P
  2235    means recognize multibyte characters.  */
  2236 
  2237 static ptrdiff_t
  2238 number_of_chars (const char *s, bool multibyte_p)
  2239 {
  2240   ptrdiff_t nchars;
  2241 
  2242   if (multibyte_p)
  2243     {
  2244       ptrdiff_t rest = strlen (s);
  2245       const unsigned char *p = (const unsigned char *) s;
  2246 
  2247       for (nchars = 0; rest > 0; ++nchars)
  2248         {
  2249           int len = BYTES_BY_CHAR_HEAD (*p);
  2250           rest -= len, p += len;
  2251         }
  2252     }
  2253   else
  2254     nchars = strlen (s);
  2255 
  2256   return nchars;
  2257 }
  2258 
  2259 
  2260 /* Compute byte position NEWPOS->bytepos corresponding to
  2261    NEWPOS->charpos.  POS is a known position in string STRING.
  2262    NEWPOS->charpos must be >= POS.charpos.  */
  2263 
  2264 static void
  2265 compute_string_pos (struct text_pos *newpos, struct text_pos pos, Lisp_Object string)
  2266 {
  2267   eassert (STRINGP (string));
  2268   eassert (CHARPOS (*newpos) >= CHARPOS (pos));
  2269 
  2270   if (STRING_MULTIBYTE (string))
  2271     *newpos = string_pos_nchars_ahead (pos, string,
  2272                                        CHARPOS (*newpos) - CHARPOS (pos));
  2273   else
  2274     BYTEPOS (*newpos) = CHARPOS (*newpos);
  2275 }
  2276 
  2277 /* EXPORT:
  2278    Return an estimation of the pixel height of mode or header lines on
  2279    frame F.  FACE_ID specifies what line's height to estimate.  */
  2280 
  2281 int
  2282 estimate_mode_line_height (struct frame *f, enum face_id face_id)
  2283 {
  2284 #ifdef HAVE_WINDOW_SYSTEM
  2285   if (FRAME_WINDOW_P (f))
  2286     {
  2287       int height = FONT_HEIGHT (FRAME_FONT (f));
  2288 
  2289       /* This function is called so early when Emacs starts that the face
  2290          cache and mode line face are not yet initialized.  */
  2291       if (FRAME_FACE_CACHE (f))
  2292         {
  2293           struct face *face = FACE_FROM_ID_OR_NULL (f, face_id);
  2294           if (face)
  2295             {
  2296               if (face->font)
  2297                 height = normal_char_height (face->font, -1);
  2298               if (face->box_horizontal_line_width > 0)
  2299                 height += 2 * face->box_horizontal_line_width;
  2300             }
  2301         }
  2302 
  2303       return height;
  2304     }
  2305 #endif
  2306 
  2307   return 1;
  2308 }
  2309 
  2310 /* Given a pixel position (PIX_X, PIX_Y) on frame F, return glyph
  2311    coordinates in (*X, *Y).  Set *BOUNDS to the rectangle that the
  2312    glyph at X, Y occupies, if BOUNDS != 0.  If NOCLIP, do
  2313    not force the value into range.  */
  2314 
  2315 void
  2316 pixel_to_glyph_coords (struct frame *f, int pix_x, int pix_y, int *x, int *y,
  2317                        NativeRectangle *bounds, bool noclip)
  2318 {
  2319 
  2320 #ifdef HAVE_WINDOW_SYSTEM
  2321   if (FRAME_WINDOW_P (f))
  2322     {
  2323       /* Arrange for the division in FRAME_PIXEL_X_TO_COL etc. to round down
  2324          even for negative values.  */
  2325       if (pix_x < 0)
  2326         pix_x -= FRAME_COLUMN_WIDTH (f) - 1;
  2327       if (pix_y < 0)
  2328         pix_y -= FRAME_LINE_HEIGHT (f) - 1;
  2329 
  2330       pix_x = FRAME_PIXEL_X_TO_COL (f, pix_x);
  2331       pix_y = FRAME_PIXEL_Y_TO_LINE (f, pix_y);
  2332 
  2333       if (bounds)
  2334         STORE_NATIVE_RECT (*bounds,
  2335                            FRAME_COL_TO_PIXEL_X (f, pix_x),
  2336                            FRAME_LINE_TO_PIXEL_Y (f, pix_y),
  2337                            FRAME_COLUMN_WIDTH (f) - 1,
  2338                            FRAME_LINE_HEIGHT (f) - 1);
  2339 
  2340       /* PXW: Should we clip pixels before converting to columns/lines?  */
  2341       if (!noclip)
  2342         {
  2343           if (pix_x < 0)
  2344             pix_x = 0;
  2345           else if (pix_x > FRAME_TOTAL_COLS (f))
  2346             pix_x = FRAME_TOTAL_COLS (f);
  2347 
  2348           if (pix_y < 0)
  2349             pix_y = 0;
  2350           else if (pix_y > FRAME_TOTAL_LINES (f))
  2351             pix_y = FRAME_TOTAL_LINES (f);
  2352         }
  2353     }
  2354 #endif
  2355 
  2356   *x = pix_x;
  2357   *y = pix_y;
  2358 }
  2359 
  2360 
  2361 /* Find the glyph under window-relative coordinates X/Y in window W.
  2362    Consider only glyphs from buffer text, i.e. no glyphs from overlay
  2363    strings.  Return in *HPOS and *VPOS the row and column number of
  2364    the glyph found.  Return in *AREA the glyph area containing X.
  2365    Value is a pointer to the glyph found or null if X/Y is not on
  2366    text, or we can't tell because W's current matrix is not up to
  2367    date.  */
  2368 
  2369 struct glyph *
  2370 x_y_to_hpos_vpos (struct window *w, int x, int y, int *hpos, int *vpos,
  2371                   int *dx, int *dy, int *area)
  2372 {
  2373   struct glyph *glyph, *end;
  2374   struct glyph_row *row = NULL;
  2375   int x0, i;
  2376 
  2377   /* Find row containing Y.  Give up if some row is not enabled.  */
  2378   for (i = 0; i < w->current_matrix->nrows; ++i)
  2379     {
  2380       row = MATRIX_ROW (w->current_matrix, i);
  2381       if (!row->enabled_p)
  2382         return NULL;
  2383       if (y >= row->y && y < MATRIX_ROW_BOTTOM_Y (row))
  2384         break;
  2385     }
  2386 
  2387   *vpos = i;
  2388   *hpos = 0;
  2389 
  2390   /* Give up if Y is not in the window.  */
  2391   if (i == w->current_matrix->nrows)
  2392     return NULL;
  2393 
  2394   /* Get the glyph area containing X.  */
  2395   if (w->pseudo_window_p)
  2396     {
  2397       *area = TEXT_AREA;
  2398       x0 = 0;
  2399     }
  2400   else
  2401     {
  2402       if (x < window_box_left_offset (w, TEXT_AREA))
  2403         {
  2404           *area = LEFT_MARGIN_AREA;
  2405           x0 = window_box_left_offset (w, LEFT_MARGIN_AREA);
  2406         }
  2407       else if (x < window_box_right_offset (w, TEXT_AREA))
  2408         {
  2409           *area = TEXT_AREA;
  2410           x0 = window_box_left_offset (w, TEXT_AREA) + min (row->x, 0);
  2411         }
  2412       else
  2413         {
  2414           *area = RIGHT_MARGIN_AREA;
  2415           x0 = window_box_left_offset (w, RIGHT_MARGIN_AREA);
  2416         }
  2417     }
  2418 
  2419   /* Find glyph containing X.  */
  2420   glyph = row->glyphs[*area];
  2421   end = glyph + row->used[*area];
  2422   x -= x0;
  2423   while (glyph < end && x >= glyph->pixel_width)
  2424     {
  2425       x -= glyph->pixel_width;
  2426       ++glyph;
  2427     }
  2428 
  2429   if (glyph == end)
  2430     return NULL;
  2431 
  2432   if (dx)
  2433     {
  2434       *dx = x;
  2435       *dy = y - (row->y + row->ascent - glyph->ascent);
  2436     }
  2437 
  2438   *hpos = glyph - row->glyphs[*area];
  2439   return glyph;
  2440 }
  2441 
  2442 /* Convert frame-relative x/y to coordinates relative to window W.
  2443    Takes pseudo-windows into account.  */
  2444 
  2445 static void
  2446 frame_to_window_pixel_xy (struct window *w, int *x, int *y)
  2447 {
  2448   if (w->pseudo_window_p)
  2449     {
  2450       /* A pseudo-window is always full-width, and starts at the
  2451          left edge of the frame, plus a frame border.  */
  2452       struct frame *f = XFRAME (w->frame);
  2453       *x -= FRAME_INTERNAL_BORDER_WIDTH (f);
  2454       *y = FRAME_TO_WINDOW_PIXEL_Y (w, *y);
  2455     }
  2456   else
  2457     {
  2458       *x -= WINDOW_LEFT_EDGE_X (w);
  2459       *y = FRAME_TO_WINDOW_PIXEL_Y (w, *y);
  2460     }
  2461 }
  2462 
  2463 #ifdef HAVE_WINDOW_SYSTEM
  2464 
  2465 /* EXPORT:
  2466    Return in RECTS[] at most N clipping rectangles for glyph string S.
  2467    Return the number of stored rectangles.  */
  2468 
  2469 int
  2470 get_glyph_string_clip_rects (struct glyph_string *s, NativeRectangle *rects, int n)
  2471 {
  2472   Emacs_Rectangle r;
  2473 
  2474   if (n <= 0)
  2475     return 0;
  2476 
  2477   if (s->row->full_width_p)
  2478     {
  2479       /* Draw full-width.  X coordinates are relative to S->w->left_col.  */
  2480       r.x = WINDOW_LEFT_EDGE_X (s->w);
  2481       if (s->row->mode_line_p)
  2482         r.width = WINDOW_PIXEL_WIDTH (s->w) - WINDOW_RIGHT_DIVIDER_WIDTH (s->w);
  2483       else
  2484         r.width = WINDOW_PIXEL_WIDTH (s->w);
  2485 
  2486       /* Unless displaying a mode or menu bar line, which are always
  2487          fully visible, clip to the visible part of the row.  */
  2488       if (s->w->pseudo_window_p)
  2489         r.height = s->row->visible_height;
  2490       else
  2491         r.height = s->height;
  2492     }
  2493   else
  2494     {
  2495       /* This is a text line that may be partially visible.  */
  2496       r.x = window_box_left (s->w, s->area);
  2497       r.width = window_box_width (s->w, s->area);
  2498       r.height = s->row->visible_height;
  2499     }
  2500 
  2501   if (s->clip_head)
  2502     if (r.x < s->clip_head->x)
  2503       {
  2504         if (r.width >= s->clip_head->x - r.x)
  2505           r.width -= s->clip_head->x - r.x;
  2506         else
  2507           r.width = 0;
  2508         r.x = s->clip_head->x;
  2509       }
  2510   if (s->clip_tail)
  2511     if (r.x + r.width > s->clip_tail->x + s->clip_tail->background_width)
  2512       {
  2513         if (s->clip_tail->x + s->clip_tail->background_width >= r.x)
  2514           r.width = s->clip_tail->x + s->clip_tail->background_width - r.x;
  2515         else
  2516           r.width = 0;
  2517       }
  2518 
  2519   /* If S draws overlapping rows, it's sufficient to use the top and
  2520      bottom of the window for clipping because this glyph string
  2521      intentionally draws over other lines.  */
  2522   if (s->for_overlaps)
  2523     {
  2524       r.y = WINDOW_TAB_LINE_HEIGHT (s->w) + WINDOW_HEADER_LINE_HEIGHT (s->w);
  2525       r.height = window_text_bottom_y (s->w) - r.y;
  2526 
  2527       /* Alas, the above simple strategy does not work for the
  2528          environments with anti-aliased text: if the same text is
  2529          drawn onto the same place multiple times, it gets thicker.
  2530          If the overlap we are processing is for the erased cursor, we
  2531          take the intersection with the rectangle of the cursor.  */
  2532       if (s->for_overlaps & OVERLAPS_ERASED_CURSOR)
  2533         {
  2534           Emacs_Rectangle rc, r_save = r;
  2535 
  2536           rc.x = WINDOW_TEXT_TO_FRAME_PIXEL_X (s->w, s->w->phys_cursor.x);
  2537           rc.y = s->w->phys_cursor.y;
  2538           rc.width = s->w->phys_cursor_width;
  2539           rc.height = s->w->phys_cursor_height;
  2540 
  2541           gui_intersect_rectangles (&r_save, &rc, &r);
  2542         }
  2543     }
  2544   else
  2545     {
  2546       /* Don't use S->y for clipping because it doesn't take partially
  2547          visible lines into account.  For example, it can be negative for
  2548          partially visible lines at the top of a window.  */
  2549       if (!s->row->full_width_p
  2550           && MATRIX_ROW_PARTIALLY_VISIBLE_AT_TOP_P (s->w, s->row))
  2551         r.y = WINDOW_TAB_LINE_HEIGHT (s->w) + WINDOW_HEADER_LINE_HEIGHT (s->w);
  2552       else
  2553         r.y = max (0, s->row->y);
  2554     }
  2555 
  2556   r.y = WINDOW_TO_FRAME_PIXEL_Y (s->w, r.y);
  2557 
  2558   /* If drawing the cursor, don't let glyph draw outside its
  2559      advertised boundaries. Cleartype does this under some circumstances.  */
  2560   if (s->hl == DRAW_CURSOR)
  2561     {
  2562       struct glyph *glyph = s->first_glyph;
  2563       int height, max_y;
  2564 
  2565       if (s->x > r.x)
  2566         {
  2567           if (r.width >= s->x - r.x)
  2568             r.width -= s->x - r.x;
  2569           else  /* R2L hscrolled row with cursor outside text area */
  2570             r.width = 0;
  2571           r.x = s->x;
  2572         }
  2573       r.width = min (r.width, glyph->pixel_width);
  2574 
  2575       /* If r.y is below window bottom, ensure that we still see a cursor.  */
  2576       height = min (glyph->ascent + glyph->descent,
  2577                     min (FRAME_LINE_HEIGHT (s->f), s->row->visible_height));
  2578       max_y = window_text_bottom_y (s->w) - height;
  2579       max_y = WINDOW_TO_FRAME_PIXEL_Y (s->w, max_y);
  2580       if (s->ybase - glyph->ascent > max_y)
  2581         {
  2582           r.y = max_y;
  2583           r.height = height;
  2584         }
  2585       else
  2586         {
  2587           /* Don't draw cursor glyph taller than our actual glyph.  */
  2588           height = max (FRAME_LINE_HEIGHT (s->f), glyph->ascent + glyph->descent);
  2589           if (height < r.height)
  2590             {
  2591               max_y = r.y + r.height;
  2592               r.y = min (max_y, max (r.y, s->ybase + glyph->descent - height));
  2593               r.height = min (max_y - r.y, height);
  2594             }
  2595         }
  2596     }
  2597 
  2598   if (s->row->clip)
  2599     {
  2600       Emacs_Rectangle r_save = r;
  2601 
  2602       if (! gui_intersect_rectangles (&r_save, s->row->clip, &r))
  2603         r.width = 0;
  2604     }
  2605 
  2606   if ((s->for_overlaps & OVERLAPS_BOTH) == 0
  2607       || ((s->for_overlaps & OVERLAPS_BOTH) == OVERLAPS_BOTH && n == 1))
  2608     {
  2609 #ifdef CONVERT_FROM_EMACS_RECT
  2610       CONVERT_FROM_EMACS_RECT (r, *rects);
  2611 #else
  2612       *rects = r;
  2613 #endif
  2614       return 1;
  2615     }
  2616   else
  2617     {
  2618       /* If we are processing overlapping and allowed to return
  2619          multiple clipping rectangles, we exclude the row of the glyph
  2620          string from the clipping rectangle.  This is to avoid drawing
  2621          the same text on the environment with anti-aliasing.  */
  2622 #ifdef CONVERT_FROM_EMACS_RECT
  2623       Emacs_Rectangle rs[2];
  2624 #else
  2625       Emacs_Rectangle *rs = rects;
  2626 #endif
  2627       int i = 0, row_y = WINDOW_TO_FRAME_PIXEL_Y (s->w, s->row->y);
  2628 
  2629       if (s->for_overlaps & OVERLAPS_PRED)
  2630         {
  2631           rs[i] = r;
  2632           if (r.y + r.height > row_y)
  2633             {
  2634               if (r.y < row_y)
  2635                 rs[i].height = row_y - r.y;
  2636               else
  2637                 rs[i].height = 0;
  2638             }
  2639           i++;
  2640         }
  2641       if (s->for_overlaps & OVERLAPS_SUCC)
  2642         {
  2643           rs[i] = r;
  2644           if (r.y < row_y + s->row->visible_height)
  2645             {
  2646               if (r.y + r.height > row_y + s->row->visible_height)
  2647                 {
  2648                   rs[i].y = row_y + s->row->visible_height;
  2649                   rs[i].height = r.y + r.height - rs[i].y;
  2650                 }
  2651               else
  2652                 rs[i].height = 0;
  2653             }
  2654           i++;
  2655         }
  2656 
  2657       n = i;
  2658 #ifdef CONVERT_FROM_EMACS_RECT
  2659       for (i = 0; i < n; i++)
  2660         CONVERT_FROM_EMACS_RECT (rs[i], rects[i]);
  2661 #endif
  2662       return n;
  2663     }
  2664 }
  2665 
  2666 /* EXPORT:
  2667    Return in *NR the clipping rectangle for glyph string S.  */
  2668 
  2669 void
  2670 get_glyph_string_clip_rect (struct glyph_string *s, NativeRectangle *nr)
  2671 {
  2672   get_glyph_string_clip_rects (s, nr, 1);
  2673 }
  2674 
  2675 
  2676 /* EXPORT:
  2677    Return the position and height of the phys cursor in window W.
  2678    Set w->phys_cursor_width to width of phys cursor.
  2679 */
  2680 
  2681 void
  2682 get_phys_cursor_geometry (struct window *w, struct glyph_row *row,
  2683                           struct glyph *glyph, int *xp, int *yp, int *heightp)
  2684 {
  2685   struct frame *f = XFRAME (WINDOW_FRAME (w));
  2686   int x, y, wd, h, h0, y0, ascent;
  2687 
  2688   /* Compute the width of the rectangle to draw.  If on a stretch
  2689      glyph, and `x-stretch-cursor' is nil, don't draw a rectangle
  2690      as wide as the glyph, but use a canonical character width
  2691      instead.  */
  2692   wd = glyph->pixel_width;
  2693 
  2694   x = w->phys_cursor.x;
  2695   if (x < 0)
  2696     {
  2697       wd += x;
  2698       x = 0;
  2699     }
  2700 
  2701   if (glyph->type == STRETCH_GLYPH
  2702       && !x_stretch_cursor_p)
  2703     wd = min (FRAME_COLUMN_WIDTH (f), wd);
  2704   w->phys_cursor_width = wd;
  2705 
  2706   /* Don't let the hollow cursor glyph descend below the glyph row's
  2707      ascent value, lest the hollow cursor looks funny.  */
  2708   y = w->phys_cursor.y;
  2709   ascent = row->ascent;
  2710   /* The test for row at ZV is for when line numbers are displayed and
  2711      point is at EOB: the cursor could then be smaller or larger than
  2712      the default face's font.  */
  2713   if (!row->ends_at_zv_p && row->ascent < glyph->ascent)
  2714     {
  2715       y -= glyph->ascent - row->ascent;
  2716       ascent = glyph->ascent;
  2717     }
  2718 
  2719   /* If y is below window bottom, ensure that we still see a cursor.  */
  2720   h0 = min (FRAME_LINE_HEIGHT (f), row->visible_height);
  2721 
  2722   h = max (h0, ascent + glyph->descent);
  2723   /* Don't let the cursor exceed the dimensions of the row, so that
  2724      the upper/lower side of the box aren't clipped.  */
  2725   h = min (h, row->height);
  2726   h0 = min (h0, ascent + glyph->descent);
  2727 
  2728   y0 = WINDOW_TAB_LINE_HEIGHT (w) + WINDOW_HEADER_LINE_HEIGHT (w);
  2729   if (y < y0)
  2730     {
  2731       h = max (h - (y0 - y) + 1, h0);
  2732       y = y0 - 1;
  2733     }
  2734   else
  2735     {
  2736       y0 = window_text_bottom_y (w) - h0;
  2737       if (y > y0)
  2738         {
  2739           h += y - y0;
  2740           y = y0;
  2741         }
  2742     }
  2743 
  2744   *xp = WINDOW_TEXT_TO_FRAME_PIXEL_X (w, x);
  2745   *yp = WINDOW_TO_FRAME_PIXEL_Y (w, y);
  2746   *heightp = h;
  2747 }
  2748 
  2749 /*
  2750  * Remember which glyph the mouse is over.
  2751  */
  2752 
  2753 void
  2754 remember_mouse_glyph (struct frame *f, int gx, int gy, NativeRectangle *rect)
  2755 {
  2756   Lisp_Object window;
  2757   struct window *w;
  2758   struct glyph_row *r, *gr, *end_row;
  2759   enum window_part part;
  2760   enum glyph_row_area area;
  2761   int x, y, width, height;
  2762 
  2763   if (mouse_fine_grained_tracking)
  2764     {
  2765       STORE_NATIVE_RECT (*rect, gx, gy, 1, 1);
  2766       return;
  2767     }
  2768 
  2769   /* Try to determine frame pixel position and size of the glyph under
  2770      frame pixel coordinates X/Y on frame F.  */
  2771 
  2772   if (window_resize_pixelwise)
  2773     {
  2774       width = height = 1;
  2775       goto virtual_glyph;
  2776     }
  2777   else if (!f->glyphs_initialized_p
  2778            || (window = window_from_coordinates (f, gx, gy, &part, false, false),
  2779                NILP (window)))
  2780     {
  2781       width = FRAME_SMALLEST_CHAR_WIDTH (f);
  2782       height = FRAME_SMALLEST_FONT_HEIGHT (f);
  2783       goto virtual_glyph;
  2784     }
  2785 
  2786   w = XWINDOW (window);
  2787   width = WINDOW_FRAME_COLUMN_WIDTH (w);
  2788   height = WINDOW_FRAME_LINE_HEIGHT (w);
  2789 
  2790   x = window_relative_x_coord (w, part, gx);
  2791   y = gy - WINDOW_TOP_EDGE_Y (w);
  2792 
  2793   r = MATRIX_FIRST_TEXT_ROW (w->current_matrix);
  2794   end_row = MATRIX_BOTTOM_TEXT_ROW (w->current_matrix, w);
  2795 
  2796   if (w->pseudo_window_p)
  2797     {
  2798       area = TEXT_AREA;
  2799       part = ON_MODE_LINE; /* Don't adjust margin. */
  2800       goto text_glyph;
  2801     }
  2802 
  2803   switch (part)
  2804     {
  2805     case ON_LEFT_MARGIN:
  2806       area = LEFT_MARGIN_AREA;
  2807       goto text_glyph;
  2808 
  2809     case ON_RIGHT_MARGIN:
  2810       area = RIGHT_MARGIN_AREA;
  2811       goto text_glyph;
  2812 
  2813     case ON_TAB_LINE:
  2814     case ON_HEADER_LINE:
  2815     case ON_MODE_LINE:
  2816       gr = (part == ON_TAB_LINE
  2817             ? MATRIX_TAB_LINE_ROW (w->current_matrix)
  2818             : (part == ON_HEADER_LINE
  2819                ? MATRIX_HEADER_LINE_ROW (w->current_matrix)
  2820                : MATRIX_MODE_LINE_ROW (w->current_matrix)));
  2821       gy = gr->y;
  2822       area = TEXT_AREA;
  2823       goto text_glyph_row_found;
  2824 
  2825     case ON_TEXT:
  2826       area = TEXT_AREA;
  2827 
  2828     text_glyph:
  2829       gr = 0; gy = 0;
  2830       for (; r <= end_row && r->enabled_p; ++r)
  2831         if (r->y + r->height > y)
  2832           {
  2833             gr = r; gy = r->y;
  2834             break;
  2835           }
  2836 
  2837     text_glyph_row_found:
  2838       if (gr && gy <= y)
  2839         {
  2840           struct glyph *g = gr->glyphs[area];
  2841           struct glyph *end = g + gr->used[area];
  2842 
  2843           height = gr->height;
  2844           for (gx = gr->x; g < end; gx += g->pixel_width, ++g)
  2845             if (gx + g->pixel_width > x)
  2846               break;
  2847 
  2848           if (g < end)
  2849             {
  2850               if (g->type == IMAGE_GLYPH)
  2851                 {
  2852                   /* Don't remember when mouse is over image, as
  2853                      image may have hot-spots.  */
  2854                   STORE_NATIVE_RECT (*rect, 0, 0, 0, 0);
  2855                   return;
  2856                 }
  2857               width = g->pixel_width;
  2858             }
  2859           else
  2860             {
  2861               /* Use nominal char spacing at end of line.  */
  2862               x -= gx;
  2863               gx += (x / width) * width;
  2864             }
  2865 
  2866           if (part != ON_MODE_LINE && part != ON_HEADER_LINE
  2867               && part != ON_TAB_LINE)
  2868             {
  2869               gx += window_box_left_offset (w, area);
  2870               /* Don't expand over the modeline to make sure the vertical
  2871                  drag cursor is shown early enough.  */
  2872               height = min (height,
  2873                             max (0, WINDOW_BOX_HEIGHT_NO_MODE_LINE (w) - gy));
  2874             }
  2875         }
  2876       else
  2877         {
  2878           /* Use nominal line height at end of window.  */
  2879           gx = (x / width) * width;
  2880           y -= gy;
  2881           gy += (y / height) * height;
  2882           if (part != ON_MODE_LINE && part != ON_HEADER_LINE
  2883               && part != ON_TAB_LINE)
  2884             /* See comment above.  */
  2885             height = min (height,
  2886                           max (0, WINDOW_BOX_HEIGHT_NO_MODE_LINE (w) - gy));
  2887         }
  2888       break;
  2889 
  2890     case ON_LEFT_FRINGE:
  2891       gx = (WINDOW_HAS_FRINGES_OUTSIDE_MARGINS (w)
  2892             ? WINDOW_LEFT_SCROLL_BAR_AREA_WIDTH (w)
  2893             : window_box_right_offset (w, LEFT_MARGIN_AREA));
  2894       width = WINDOW_LEFT_FRINGE_WIDTH (w);
  2895       goto row_glyph;
  2896 
  2897     case ON_RIGHT_FRINGE:
  2898       gx = (WINDOW_HAS_FRINGES_OUTSIDE_MARGINS (w)
  2899             ? window_box_right_offset (w, RIGHT_MARGIN_AREA)
  2900             : window_box_right_offset (w, TEXT_AREA));
  2901       if (WINDOW_RIGHT_DIVIDER_WIDTH (w) == 0
  2902           && !WINDOW_HAS_VERTICAL_SCROLL_BAR (w)
  2903           && !WINDOW_RIGHTMOST_P (w))
  2904         if (gx < WINDOW_PIXEL_WIDTH (w) - width)
  2905           /* Make sure the vertical border can get her own glyph to the
  2906              right of the one we build here.  */
  2907           width = WINDOW_RIGHT_FRINGE_WIDTH (w) - width;
  2908         else
  2909           width = WINDOW_PIXEL_WIDTH (w) - gx;
  2910       else
  2911         width = WINDOW_RIGHT_FRINGE_WIDTH (w);
  2912 
  2913       goto row_glyph;
  2914 
  2915     case ON_VERTICAL_BORDER:
  2916       gx = WINDOW_PIXEL_WIDTH (w) - width;
  2917       goto row_glyph;
  2918 
  2919     case ON_VERTICAL_SCROLL_BAR:
  2920       gx = (WINDOW_HAS_VERTICAL_SCROLL_BAR_ON_LEFT (w)
  2921             ? 0
  2922             : (window_box_right_offset (w, RIGHT_MARGIN_AREA)
  2923                + (WINDOW_HAS_FRINGES_OUTSIDE_MARGINS (w)
  2924                   ? WINDOW_RIGHT_FRINGE_WIDTH (w)
  2925                   : 0)));
  2926       width = WINDOW_SCROLL_BAR_AREA_WIDTH (w);
  2927 
  2928     row_glyph:
  2929       gr = 0, gy = 0;
  2930       for (; r <= end_row && r->enabled_p; ++r)
  2931         if (r->y + r->height > y)
  2932           {
  2933             gr = r; gy = r->y;
  2934             break;
  2935           }
  2936 
  2937       if (gr && gy <= y)
  2938         height = gr->height;
  2939       else
  2940         {
  2941           /* Use nominal line height at end of window.  */
  2942           y -= gy;
  2943           gy += (y / height) * height;
  2944         }
  2945       break;
  2946 
  2947     case ON_RIGHT_DIVIDER:
  2948       gx = WINDOW_PIXEL_WIDTH (w) - WINDOW_RIGHT_DIVIDER_WIDTH (w);
  2949       width = WINDOW_RIGHT_DIVIDER_WIDTH (w);
  2950       gy = 0;
  2951       /* The bottom divider prevails. */
  2952       height = WINDOW_PIXEL_HEIGHT (w) - WINDOW_BOTTOM_DIVIDER_WIDTH (w);
  2953       goto add_edge;
  2954 
  2955     case ON_BOTTOM_DIVIDER:
  2956       gx = 0;
  2957       width = WINDOW_PIXEL_WIDTH (w);
  2958       gy = WINDOW_PIXEL_HEIGHT (w) - WINDOW_BOTTOM_DIVIDER_WIDTH (w);
  2959       height = WINDOW_BOTTOM_DIVIDER_WIDTH (w);
  2960       goto add_edge;
  2961 
  2962     default:
  2963       ;
  2964     virtual_glyph:
  2965       /* If there is no glyph under the mouse, then we divide the screen
  2966          into a grid of the smallest glyph in the frame, and use that
  2967          as our "glyph".  */
  2968 
  2969       /* Arrange for the division in FRAME_PIXEL_X_TO_COL etc. to
  2970          round down even for negative values.  */
  2971       if (gx < 0)
  2972         gx -= width - 1;
  2973       if (gy < 0)
  2974         gy -= height - 1;
  2975 
  2976       gx = (gx / width) * width;
  2977       gy = (gy / height) * height;
  2978 
  2979       goto store_rect;
  2980     }
  2981 
  2982  add_edge:
  2983   gx += WINDOW_LEFT_EDGE_X (w);
  2984   gy += WINDOW_TOP_EDGE_Y (w);
  2985 
  2986  store_rect:
  2987   STORE_NATIVE_RECT (*rect, gx, gy, width, height);
  2988 
  2989   /* Visible feedback for debugging.  */
  2990 #if false && defined HAVE_X_WINDOWS
  2991   XDrawRectangle (FRAME_X_DISPLAY (f), FRAME_X_DRAWABLE (f),
  2992                   f->output_data.x->normal_gc,
  2993                   gx, gy, width, height);
  2994 #endif
  2995 }
  2996 
  2997 
  2998 #endif /* HAVE_WINDOW_SYSTEM */
  2999 
  3000 static void
  3001 adjust_window_ends (struct window *w, struct glyph_row *row, bool current)
  3002 {
  3003   eassert (w);
  3004   w->window_end_pos = Z - MATRIX_ROW_END_CHARPOS (row);
  3005   w->window_end_bytepos = Z_BYTE - MATRIX_ROW_END_BYTEPOS (row);
  3006   w->window_end_vpos
  3007     = MATRIX_ROW_VPOS (row, current ? w->current_matrix : w->desired_matrix);
  3008 }
  3009 
  3010 static bool
  3011 hscrolling_current_line_p (struct window *w)
  3012 {
  3013   return (!w->suspend_auto_hscroll
  3014           && EQ (Fbuffer_local_value (Qauto_hscroll_mode, w->contents),
  3015                  Qcurrent_line));
  3016 }
  3017 
  3018 /***********************************************************************
  3019                         Lisp form evaluation
  3020  ***********************************************************************/
  3021 
  3022 /* Error handler for safe_eval and safe_call.  */
  3023 
  3024 static Lisp_Object
  3025 safe_eval_handler (Lisp_Object arg, ptrdiff_t nargs, Lisp_Object *args)
  3026 {
  3027   add_to_log ("Error during redisplay: %S signaled %S",
  3028               Flist (nargs, args), arg);
  3029   return Qnil;
  3030 }
  3031 
  3032 /* Call function FUNC with the rest of NARGS - 1 arguments
  3033    following.  Return the result, or nil if something went
  3034    wrong.  Prevent redisplay during the evaluation.  */
  3035 
  3036 static Lisp_Object
  3037 safe__call (bool inhibit_quit, ptrdiff_t nargs, Lisp_Object func, va_list ap)
  3038 {
  3039   Lisp_Object val;
  3040 
  3041   if (inhibit_eval_during_redisplay)
  3042     val = Qnil;
  3043   else
  3044     {
  3045       ptrdiff_t i;
  3046       specpdl_ref count = SPECPDL_INDEX ();
  3047       Lisp_Object *args;
  3048       USE_SAFE_ALLOCA;
  3049       SAFE_ALLOCA_LISP (args, nargs);
  3050 
  3051       args[0] = func;
  3052       for (i = 1; i < nargs; i++)
  3053         args[i] = va_arg (ap, Lisp_Object);
  3054 
  3055       specbind (Qinhibit_redisplay, Qt);
  3056       if (inhibit_quit)
  3057         specbind (Qinhibit_quit, Qt);
  3058       /* Use Qt to ensure debugger does not run,
  3059          so there is no possibility of wanting to redisplay.  */
  3060       val = internal_condition_case_n (Ffuncall, nargs, args, Qt,
  3061                                        safe_eval_handler);
  3062       val = SAFE_FREE_UNBIND_TO (count, val);
  3063     }
  3064 
  3065   return val;
  3066 }
  3067 
  3068 Lisp_Object
  3069 safe_call (ptrdiff_t nargs, Lisp_Object func, ...)
  3070 {
  3071   Lisp_Object retval;
  3072   va_list ap;
  3073 
  3074   va_start (ap, func);
  3075   retval = safe__call (false, nargs, func, ap);
  3076   va_end (ap);
  3077   return retval;
  3078 }
  3079 
  3080 /* Call function FN with one argument ARG.
  3081    Return the result, or nil if something went wrong.  */
  3082 
  3083 Lisp_Object
  3084 safe_call1 (Lisp_Object fn, Lisp_Object arg)
  3085 {
  3086   return safe_call (2, fn, arg);
  3087 }
  3088 
  3089 static Lisp_Object
  3090 safe__call1 (bool inhibit_quit, Lisp_Object fn, ...)
  3091 {
  3092   Lisp_Object retval;
  3093   va_list ap;
  3094 
  3095   va_start (ap, fn);
  3096   retval = safe__call (inhibit_quit, 2, fn, ap);
  3097   va_end (ap);
  3098   return retval;
  3099 }
  3100 
  3101 Lisp_Object
  3102 safe_eval (Lisp_Object sexpr)
  3103 {
  3104   return safe__call1 (false, Qeval, sexpr);
  3105 }
  3106 
  3107 static Lisp_Object
  3108 safe__eval (bool inhibit_quit, Lisp_Object sexpr)
  3109 {
  3110   return safe__call1 (inhibit_quit, Qeval, sexpr);
  3111 }
  3112 
  3113 /* Call function FN with two arguments ARG1 and ARG2.
  3114    Return the result, or nil if something went wrong.  */
  3115 
  3116 Lisp_Object
  3117 safe_call2 (Lisp_Object fn, Lisp_Object arg1, Lisp_Object arg2)
  3118 {
  3119   return safe_call (3, fn, arg1, arg2);
  3120 }
  3121 
  3122 
  3123 
  3124 /***********************************************************************
  3125                               Debugging
  3126  ***********************************************************************/
  3127 
  3128 /* Define CHECK_IT to perform sanity checks on iterators.
  3129    This is for debugging.  It is too slow to do unconditionally.  */
  3130 
  3131 static void
  3132 CHECK_IT (struct it *it)
  3133 {
  3134 #if false
  3135   if (it->method == GET_FROM_STRING)
  3136     {
  3137       eassert (STRINGP (it->string));
  3138       eassert (IT_STRING_CHARPOS (*it) >= 0);
  3139     }
  3140   else
  3141     {
  3142       eassert (IT_STRING_CHARPOS (*it) < 0);
  3143       if (it->method == GET_FROM_BUFFER)
  3144         {
  3145           /* Check that character and byte positions agree.  */
  3146           eassert (IT_CHARPOS (*it) == BYTE_TO_CHAR (IT_BYTEPOS (*it)));
  3147         }
  3148     }
  3149 
  3150   if (it->dpvec)
  3151     eassert (it->current.dpvec_index >= 0);
  3152   else
  3153     eassert (it->current.dpvec_index < 0);
  3154 #endif
  3155 }
  3156 
  3157 
  3158 /* Check that the window end of window W is what we expect it
  3159    to be---the last row in the current matrix displaying text.  */
  3160 
  3161 static void
  3162 CHECK_WINDOW_END (struct window *w)
  3163 {
  3164 #if defined GLYPH_DEBUG && defined ENABLE_CHECKING
  3165   if (!MINI_WINDOW_P (w) && w->window_end_valid)
  3166     {
  3167       struct glyph_row *row;
  3168       eassert ((row = MATRIX_ROW (w->current_matrix, w->window_end_vpos),
  3169                 !row->enabled_p
  3170                 || MATRIX_ROW_DISPLAYS_TEXT_P (row)
  3171                 || MATRIX_ROW_VPOS (row, w->current_matrix) == 0));
  3172     }
  3173 #endif
  3174 }
  3175 
  3176 /***********************************************************************
  3177                        Iterator initialization
  3178  ***********************************************************************/
  3179 
  3180 /* Initialize IT for displaying current_buffer in window W, starting
  3181    at character position CHARPOS.  CHARPOS < 0 means that no buffer
  3182    position is specified which is useful when the iterator is assigned
  3183    a position later.  BYTEPOS is the byte position corresponding to
  3184    CHARPOS.
  3185 
  3186    If ROW is not null, calls to produce_glyphs with IT as parameter
  3187    will produce glyphs in that row.
  3188 
  3189    BASE_FACE_ID is the id of a base face to use.  It must be one of
  3190    DEFAULT_FACE_ID for normal text, MODE_LINE_ACTIVE_FACE_ID,
  3191    MODE_LINE_INACTIVE_FACE_ID, or HEADER_LINE_FACE_ID for displaying
  3192    mode lines, or TOOL_BAR_FACE_ID for displaying the tool-bar.
  3193 
  3194    If ROW is null and BASE_FACE_ID is equal to MODE_LINE_ACTIVE_FACE_ID,
  3195    MODE_LINE_INACTIVE_FACE_ID, or HEADER_LINE_FACE_ID, the iterator
  3196    will be initialized to use the corresponding mode line glyph row of
  3197    the desired matrix of W.  */
  3198 
  3199 void
  3200 init_iterator (struct it *it, struct window *w,
  3201                ptrdiff_t charpos, ptrdiff_t bytepos,
  3202                struct glyph_row *row, enum face_id base_face_id)
  3203 {
  3204   enum face_id remapped_base_face_id = base_face_id;
  3205   int body_width = 0, body_height = 0;
  3206 
  3207   /* Some precondition checks.  */
  3208   eassert (w != NULL && it != NULL);
  3209   eassert (charpos < 0 || (charpos >= BUF_BEG (current_buffer)
  3210                            && charpos <= ZV));
  3211 
  3212   /* If face attributes have been changed since the last redisplay,
  3213      free realized faces now because they depend on face definitions
  3214      that might have changed.  Don't free faces while there might be
  3215      desired matrices pending which reference these faces.  */
  3216   if (!inhibit_free_realized_faces)
  3217     {
  3218       if (face_change)
  3219         {
  3220           face_change = false;
  3221           XFRAME (w->frame)->face_change = 0;
  3222           free_all_realized_faces (Qnil);
  3223         }
  3224       else if (XFRAME (w->frame)->face_change)
  3225         {
  3226           XFRAME (w->frame)->face_change = 0;
  3227           free_all_realized_faces (w->frame);
  3228         }
  3229     }
  3230 
  3231   /* Perhaps remap BASE_FACE_ID to a user-specified alternative.  */
  3232   if (! NILP (Vface_remapping_alist))
  3233     remapped_base_face_id
  3234       = lookup_basic_face (w, XFRAME (w->frame), base_face_id);
  3235 
  3236   /* Use one of the mode line rows of W's desired matrix if
  3237      appropriate.  */
  3238   if (row == NULL)
  3239     {
  3240       if (base_face_id == MODE_LINE_ACTIVE_FACE_ID
  3241           || base_face_id == MODE_LINE_INACTIVE_FACE_ID)
  3242         row = MATRIX_MODE_LINE_ROW (w->desired_matrix);
  3243       else if (base_face_id == TAB_LINE_FACE_ID)
  3244         row = MATRIX_TAB_LINE_ROW (w->desired_matrix);
  3245       else if (base_face_id == HEADER_LINE_FACE_ID)
  3246         {
  3247           /* Header line row depends on whether tab line is enabled.  */
  3248           w->desired_matrix->tab_line_p = window_wants_tab_line (w);
  3249           row = MATRIX_HEADER_LINE_ROW (w->desired_matrix);
  3250         }
  3251     }
  3252 
  3253   /* Clear IT, and set it->object and other IT's Lisp objects to Qnil.
  3254      Other parts of redisplay rely on that.  */
  3255   memclear (it, sizeof *it);
  3256   it->current.overlay_string_index = -1;
  3257   it->current.dpvec_index = -1;
  3258   it->base_face_id = remapped_base_face_id;
  3259   IT_STRING_CHARPOS (*it) = IT_STRING_BYTEPOS (*it) = -1;
  3260   it->paragraph_embedding = L2R;
  3261   it->bidi_it.w = w;
  3262 
  3263   /* The window in which we iterate over current_buffer:  */
  3264   XSETWINDOW (it->window, w);
  3265   it->w = w;
  3266   it->f = XFRAME (w->frame);
  3267 
  3268   it->cmp_it.id = -1;
  3269   it->cmp_it.parent_it = it;
  3270 
  3271   if (max_redisplay_ticks > 0)
  3272     update_redisplay_ticks (0, w);
  3273 
  3274   /* Extra space between lines (on window systems only).  */
  3275   if (base_face_id == DEFAULT_FACE_ID
  3276       && FRAME_WINDOW_P (it->f))
  3277     {
  3278       if (FIXNATP (BVAR (current_buffer, extra_line_spacing)))
  3279         it->extra_line_spacing = XFIXNAT (BVAR (current_buffer, extra_line_spacing));
  3280       else if (FLOATP (BVAR (current_buffer, extra_line_spacing)))
  3281         it->extra_line_spacing = (XFLOAT_DATA (BVAR (current_buffer, extra_line_spacing))
  3282                                   * FRAME_LINE_HEIGHT (it->f));
  3283       else if (it->f->extra_line_spacing > 0)
  3284         it->extra_line_spacing = it->f->extra_line_spacing;
  3285     }
  3286 
  3287   /* If realized faces have been removed, e.g. because of face
  3288      attribute changes of named faces, recompute them.  When running
  3289      in batch mode, the face cache of the initial frame is null.  If
  3290      we happen to get called, make a dummy face cache.  */
  3291   if (FRAME_FACE_CACHE (it->f) == NULL)
  3292     init_frame_faces (it->f);
  3293   if (FRAME_FACE_CACHE (it->f)->used == 0)
  3294     recompute_basic_faces (it->f);
  3295 
  3296   it->override_ascent = -1;
  3297 
  3298   /* Are control characters displayed as `^C'?  */
  3299   it->ctl_arrow_p = !NILP (BVAR (current_buffer, ctl_arrow));
  3300 
  3301   /* -1 means everything between a CR and the following line end
  3302      is invisible.  >0 means lines indented more than this value are
  3303      invisible.  */
  3304   it->selective = (FIXNUMP (BVAR (current_buffer, selective_display))
  3305                    ? (clip_to_bounds
  3306                       (-1, XFIXNUM (BVAR (current_buffer, selective_display)),
  3307                        PTRDIFF_MAX))
  3308                    : (!NILP (BVAR (current_buffer, selective_display))
  3309                       ? -1 : 0));
  3310   it->selective_display_ellipsis_p
  3311     = !NILP (BVAR (current_buffer, selective_display_ellipses));
  3312 
  3313   /* Display table to use.  */
  3314   it->dp = window_display_table (w);
  3315 
  3316   /* Are multibyte characters enabled in current_buffer?  */
  3317   it->multibyte_p = !NILP (BVAR (current_buffer, enable_multibyte_characters));
  3318 
  3319   it->tab_width = SANE_TAB_WIDTH (current_buffer);
  3320 
  3321   /* Are lines in the display truncated?  */
  3322   if (TRUNCATE != 0)
  3323     it->line_wrap = TRUNCATE;
  3324   if (base_face_id == DEFAULT_FACE_ID
  3325       && !it->w->hscroll
  3326       && (WINDOW_FULL_WIDTH_P (it->w)
  3327           || NILP (Vtruncate_partial_width_windows)
  3328           || (FIXNUMP (Vtruncate_partial_width_windows)
  3329               /* PXW: Shall we do something about this?  */
  3330               && (XFIXNUM (Vtruncate_partial_width_windows)
  3331                   <= WINDOW_TOTAL_COLS (it->w))))
  3332       && NILP (BVAR (current_buffer, truncate_lines)))
  3333     it->line_wrap = NILP (BVAR (current_buffer, word_wrap))
  3334       ? WINDOW_WRAP : WORD_WRAP;
  3335 
  3336   /* Get dimensions of truncation and continuation glyphs.  These are
  3337      displayed as fringe bitmaps under X, but we need them for such
  3338      frames when the fringes are turned off.  The no_special_glyphs slot
  3339      of the iterator's frame, when set, suppresses their display - by
  3340      default for tooltip frames and when set via the 'no-special-glyphs'
  3341      frame parameter.  */
  3342 #ifdef HAVE_WINDOW_SYSTEM
  3343   if (!(FRAME_WINDOW_P (it->f) && it->f->no_special_glyphs))
  3344 #endif
  3345     {
  3346       if (it->line_wrap == TRUNCATE)
  3347         {
  3348           /* We will need the truncation glyph.  */
  3349           eassert (it->glyph_row == NULL);
  3350           produce_special_glyphs (it, IT_TRUNCATION);
  3351           it->truncation_pixel_width = it->pixel_width;
  3352         }
  3353       else
  3354         {
  3355           /* We will need the continuation glyph.  */
  3356           eassert (it->glyph_row == NULL);
  3357           produce_special_glyphs (it, IT_CONTINUATION);
  3358           it->continuation_pixel_width = it->pixel_width;
  3359         }
  3360     }
  3361 
  3362   /* Reset these values to zero because the produce_special_glyphs
  3363      above has changed them.  */
  3364   it->pixel_width = it->ascent = it->descent = 0;
  3365   it->phys_ascent = it->phys_descent = 0;
  3366 
  3367   /* Set this after getting the dimensions of truncation and
  3368      continuation glyphs, so that we don't produce glyphs when calling
  3369      produce_special_glyphs, above.  */
  3370   it->glyph_row = row;
  3371   it->area = TEXT_AREA;
  3372 
  3373   /* Get the dimensions of the display area.  The display area
  3374      consists of the visible window area plus a horizontally scrolled
  3375      part to the left of the window.  All x-values are relative to the
  3376      start of this total display area.  */
  3377   if (base_face_id != DEFAULT_FACE_ID)
  3378     {
  3379       /* Mode lines, menu bar in terminal frames.  */
  3380       it->first_visible_x = 0;
  3381       it->last_visible_x =
  3382         WINDOW_PIXEL_WIDTH (w) - WINDOW_RIGHT_DIVIDER_WIDTH (w);
  3383     }
  3384   else
  3385     {
  3386       /* When hscrolling only the current line, don't apply the
  3387          hscroll here, it will be applied by display_line when it gets
  3388          to laying out the line showing point.  However, if the
  3389          window's min_hscroll is positive, the user specified a lower
  3390          bound for automatic hscrolling, so they expect the
  3391          non-current lines to obey that hscroll amount.  */
  3392       if (hscrolling_current_line_p (w))
  3393         {
  3394           if (w->min_hscroll > 0)
  3395             it->first_visible_x = w->min_hscroll * FRAME_COLUMN_WIDTH (it->f);
  3396           else
  3397             it->first_visible_x = 0;
  3398         }
  3399       else
  3400         it->first_visible_x =
  3401           window_hscroll_limited (w, it->f) * FRAME_COLUMN_WIDTH (it->f);
  3402 
  3403       body_width = window_box_width (w, TEXT_AREA);
  3404       if (!w->pseudo_window_p && !MINI_WINDOW_P (w)
  3405           && body_width != w->old_body_pixel_width)
  3406         FRAME_WINDOW_CHANGE (it->f) = true;
  3407       it->last_visible_x = it->first_visible_x + body_width;
  3408 
  3409       /* If we truncate lines, leave room for the truncation glyph(s) at
  3410          the right margin.  Otherwise, leave room for the continuation
  3411          glyph(s).  Done only if the window has no right fringe.  */
  3412       if (WINDOW_RIGHT_FRINGE_WIDTH (it->w) == 0)
  3413         {
  3414           if (it->line_wrap == TRUNCATE)
  3415             it->last_visible_x -= it->truncation_pixel_width;
  3416           else
  3417             it->last_visible_x -= it->continuation_pixel_width;
  3418         }
  3419 
  3420       it->tab_line_p = window_wants_tab_line (w);
  3421       it->header_line_p = window_wants_header_line (w);
  3422       body_height = WINDOW_TAB_LINE_HEIGHT (w) + WINDOW_HEADER_LINE_HEIGHT (w);
  3423       it->current_y =  body_height + w->vscroll;
  3424     }
  3425 
  3426   /* Leave room for a border glyph.  */
  3427   if (!FRAME_WINDOW_P (it->f)
  3428       && !WINDOW_RIGHTMOST_P (it->w))
  3429     it->last_visible_x -= 1;
  3430 
  3431   it->last_visible_y = window_text_bottom_y (w);
  3432   body_height += it->last_visible_y;
  3433   if (!w->pseudo_window_p && !MINI_WINDOW_P (w)
  3434       && body_height != w->old_body_pixel_height)
  3435     FRAME_WINDOW_CHANGE (it->f) = true;
  3436 
  3437   /* For mode lines and alike, arrange for the first glyph having a
  3438      left box line if the face specifies a box.  */
  3439   if (base_face_id != DEFAULT_FACE_ID)
  3440     {
  3441       struct face *face;
  3442 
  3443       it->face_id = remapped_base_face_id;
  3444 
  3445       /* If we have a boxed mode line, make the first character appear
  3446          with a left box line.  */
  3447       face = FACE_FROM_ID_OR_NULL (it->f, remapped_base_face_id);
  3448       if (face && face->box != FACE_NO_BOX)
  3449         {
  3450           int box_thickness = face->box_vertical_line_width;
  3451           it->face_box_p = true;
  3452           it->start_of_box_run_p = true;
  3453           /* Make sure we will have enough horizontal space to add the
  3454              right box line at the end.  */
  3455           if (box_thickness > 0)
  3456             it->last_visible_x -= box_thickness;
  3457         }
  3458     }
  3459 
  3460   /* If a buffer position was specified, set the iterator there,
  3461      getting overlays and face properties from that position.  */
  3462   if (charpos >= BUF_BEG (current_buffer))
  3463     {
  3464       it->stop_charpos = charpos;
  3465       it->end_charpos = ZV;
  3466       eassert (charpos == BYTE_TO_CHAR (bytepos));
  3467       IT_CHARPOS (*it) = charpos;
  3468       IT_BYTEPOS (*it) = bytepos;
  3469 
  3470       /* We will rely on `reseat' to set this up properly, via
  3471          handle_face_prop.  */
  3472       it->face_id = it->base_face_id;
  3473 
  3474       it->start = it->current;
  3475       /* Do we need to reorder bidirectional text?  Not if this is a
  3476          unibyte buffer: by definition, none of the single-byte
  3477          characters are strong R2L, so no reordering is needed.  And
  3478          bidi.c doesn't support unibyte buffers anyway.  Also, don't
  3479          reorder while we are loading loadup.el, since the tables of
  3480          character properties needed for reordering are not yet
  3481          available.  */
  3482       it->bidi_p =
  3483         !redisplay__inhibit_bidi
  3484         && !NILP (BVAR (current_buffer, bidi_display_reordering))
  3485         && it->multibyte_p;
  3486 
  3487       /* If we are to reorder bidirectional text, init the bidi
  3488          iterator.  */
  3489       if (it->bidi_p)
  3490         {
  3491           /*  Since we don't know at this point whether there will be
  3492               any R2L lines in the window, we reserve space for
  3493               truncation/continuation glyphs even if only the left
  3494               fringe is absent.  */
  3495           if (base_face_id == DEFAULT_FACE_ID
  3496               && WINDOW_LEFT_FRINGE_WIDTH (it->w) == 0
  3497               && WINDOW_RIGHT_FRINGE_WIDTH (it->w) != 0)
  3498             {
  3499               if (it->line_wrap == TRUNCATE)
  3500                 it->last_visible_x -= it->truncation_pixel_width;
  3501               else
  3502                 it->last_visible_x -= it->continuation_pixel_width;
  3503             }
  3504           /* Note the paragraph direction that this buffer wants to
  3505              use.  */
  3506           if (EQ (BVAR (current_buffer, bidi_paragraph_direction),
  3507                   Qleft_to_right))
  3508             it->paragraph_embedding = L2R;
  3509           else if (EQ (BVAR (current_buffer, bidi_paragraph_direction),
  3510                        Qright_to_left))
  3511             it->paragraph_embedding = R2L;
  3512           else
  3513             it->paragraph_embedding = NEUTRAL_DIR;
  3514           bidi_unshelve_cache (NULL, false);
  3515           bidi_init_it (charpos, IT_BYTEPOS (*it), FRAME_WINDOW_P (it->f),
  3516                         &it->bidi_it);
  3517         }
  3518 
  3519       /* This is set only when long_line_optimizations_p is non-zero
  3520          for the current buffer.  */
  3521       it->medium_narrowing_begv = 0;
  3522 
  3523       /* Compute faces etc.  */
  3524       reseat (it, it->current.pos, true);
  3525     }
  3526 
  3527   CHECK_IT (it);
  3528 }
  3529 
  3530 /* How Emacs deals with long lines.
  3531 
  3532    (1) When a buffer is about to be (re)displayed, 'redisplay_window'
  3533    detects, with a heuristic, whether it contains long lines.
  3534 
  3535    This happens in 'redisplay_window' because it is only displaying
  3536    buffers with long lines that is problematic.  In other words, none
  3537    of the optimizations described below is ever used in buffers that
  3538    are never displayed.
  3539 
  3540    This happens with a heuristic, which checks whether a buffer
  3541    contains long lines, each time its contents have changed "enough"
  3542    between two redisplay cycles, because a buffer without long lines
  3543    can become a buffer with long lines at any time, for example after
  3544    a yank command, or after a replace command, or while the output of
  3545    an external process is inserted in a buffer.
  3546 
  3547    When Emacs has detected that a buffer contains long lines, the
  3548    buffer-local variable 'long_line_optimizations_p' (in 'struct
  3549    buffer') is set, and Emacs does not try to detect whether the
  3550    buffer does or does not contain long lines anymore.
  3551 
  3552    What a long line is depends on the variable 'long-line-threshold',
  3553    whose default value is 50000 (characters).
  3554 
  3555    (2) When a buffer with long lines is (re)displayed, the amount of
  3556    data that the display routines consider is, in a few well-chosen
  3557    places, limited with a temporary restriction, whose bounds are
  3558    calculated with the functions below.
  3559 
  3560    (2.1) 'get_small_narrowing_begv' is used to create a restriction
  3561    which starts a few hundred characters before point.  The exact
  3562    number of characters depends on the width of the window in which
  3563    the buffer is displayed.
  3564 
  3565    There is no corresponding 'get_small_narrowing_zv' function,
  3566    because it is not necessary to set the end limit of that
  3567    restriction.
  3568 
  3569    This restriction is used in four places, namely:
  3570    'back_to_previous_line_start' and 'move_it_vertically_backward'
  3571    (with the 'SET_WITH_NARROWED_BEGV' macro), and in
  3572    'composition_compute_stop_pos' and 'find_automatic_composition' (in
  3573    a conditional statement depending on 'long_line_optimizations_p').
  3574 
  3575    (2.2) 'get_medium_narrowing_begv' is used to create a restriction
  3576    which starts a few thousand characters before point.  The exact
  3577    number of characters depends on the size (width and height) of the
  3578    window in which the buffer is displayed.  For performance reasons,
  3579    the return value of that function is cached in 'struct it', in the
  3580    'medium_narrowing_begv' field.
  3581 
  3582    The corresponding function 'get_medium_narrowing_zv' (and
  3583    'medium_narrowing_zv' field in 'struct it') is not used to set the
  3584    end limit of the restriction, which is again unnecessary, but to
  3585    determine, in 'reseat', whether the iterator has moved far enough
  3586    from its original position, and whether the start position of the
  3587    restriction must be computed anew.
  3588 
  3589    This restriction is used in a single place:
  3590    'get_visually_first_element', with the 'SET_WITH_NARROWED_BEGV'
  3591    macro.
  3592 
  3593    (2.3) 'get_large_narrowing_begv' and 'get_large_narrowing_zv' are
  3594    used to create a restriction which starts a few hundred thousand
  3595    characters before point and ends a few hundred thousand characters
  3596    after point.  The size of that restriction depends on the variable
  3597    'long-line-optimizations-region-size', whose default value is
  3598    500000 (characters); it can be adjusted by a few hundred characters
  3599    depending on 'long-line-optimizations-bol-search-limit', whose
  3600    default value is 128 (characters).
  3601 
  3602    For performance reasons again, the return values of these functions
  3603    are stored in the 'large_narrowing_begv' and 'large_narrowing_zv'
  3604    fields in 'struct it'.
  3605 
  3606    The restriction defined by these values is used around three
  3607    low-level hooks: around 'fontification-functions', in
  3608    'handle_fontified_prop', and around 'pre-command-hook' and
  3609    'post-command-hook', in 'safe_run_hooks_maybe_narrowed', which is
  3610    called in 'command_loop_1'.  These restrictions are set around
  3611    these hooks with 'labeled_narrow_to_region'; the restrictions are
  3612    labeled, and cannot be removed with a call to 'widen', but can be
  3613    removed with 'without-restriction' with a :label argument.
  3614 */
  3615 
  3616 static int
  3617 get_narrowed_width (struct window *w)
  3618 {
  3619   /* In a character-only terminal, only one font size is used, so we
  3620      can use a smaller factor.  */
  3621   int fact = FRAME_WINDOW_P (XFRAME (w->frame)) ? 3 : 2;
  3622   /* If the window has no fringes (in a character-only terminal or in
  3623      a GUI frame without fringes), subtract 1 from the width for the
  3624      '\' line wrapping character.  */
  3625   int width = window_body_width (w, WINDOW_BODY_IN_CANONICAL_CHARS)
  3626     - ((WINDOW_RIGHT_FRINGE_WIDTH (w) == 0
  3627         || WINDOW_LEFT_FRINGE_WIDTH (w) == 0) ? 1 : 0);
  3628   return fact * max (1, width);
  3629 }
  3630 
  3631 static int
  3632 get_narrowed_len (struct window *w)
  3633 {
  3634   int height = window_body_height (w, WINDOW_BODY_IN_CANONICAL_CHARS);
  3635   return get_narrowed_width (w) * max (1, height);
  3636 }
  3637 
  3638 static ptrdiff_t
  3639 get_medium_narrowing_begv (struct window *w, ptrdiff_t pos)
  3640 {
  3641   int len = get_narrowed_len (w);
  3642   return max ((pos / len - 1) * len, BEGV);
  3643 }
  3644 
  3645 static ptrdiff_t
  3646 get_medium_narrowing_zv (struct window *w, ptrdiff_t pos)
  3647 {
  3648   int len = get_narrowed_len (w);
  3649   return min ((pos / len + 1) * len, ZV);
  3650 }
  3651 
  3652 /* Find the position of the last BOL before POS, unless it is too far
  3653    away.  The buffer portion in which the search occurs is gradually
  3654    enlarged: [POS-500..POS], [POS-5500..POS-500],
  3655    [POS-55500..POS-5500], and finally [POS-555500..POS-55500].  Return
  3656    BEGV-1 if no BOL was found in [POS-555500..POS].  */
  3657 static ptrdiff_t
  3658 get_nearby_bol_pos (ptrdiff_t pos)
  3659 {
  3660   ptrdiff_t start, pos_bytepos, cur, next, found, bol = BEGV - 1, init_pos = pos;
  3661   int dist;
  3662   for (dist = 500; dist <= 500000; dist *= 10)
  3663     {
  3664       pos_bytepos = pos == BEGV ? BEGV_BYTE : CHAR_TO_BYTE (pos);
  3665       start = pos - dist < BEGV ? BEGV : pos - dist;
  3666       for (cur = start; cur < pos; cur = next)
  3667         {
  3668           next = find_newline1 (cur, CHAR_TO_BYTE (cur),
  3669                                 pos, pos_bytepos,
  3670                                 1, &found, NULL, false);
  3671           if (found)
  3672             bol = next;
  3673           else
  3674             break;
  3675         }
  3676       if (bol >= BEGV || start == BEGV)
  3677         break;
  3678       else
  3679         pos = pos - dist < BEGV ? BEGV : pos - dist;
  3680     }
  3681   eassert (bol <= init_pos);
  3682   return bol;
  3683 }
  3684 
  3685 ptrdiff_t
  3686 get_small_narrowing_begv (struct window *w, ptrdiff_t pos)
  3687 {
  3688   int len = get_narrowed_width (w);
  3689   ptrdiff_t bol_pos = max (get_nearby_bol_pos (pos), BEGV);
  3690   return max (bol_pos + ((pos - bol_pos) / len - 1) * len, BEGV);
  3691 }
  3692 
  3693 ptrdiff_t
  3694 get_large_narrowing_begv (ptrdiff_t pos)
  3695 {
  3696   if (long_line_optimizations_region_size <= 0)
  3697     return BEGV;
  3698   int len = long_line_optimizations_region_size / 2;
  3699   int begv = max (pos - len, BEGV);
  3700   int limit = long_line_optimizations_bol_search_limit;
  3701   while (limit > 0)
  3702     {
  3703       if (begv == BEGV || FETCH_BYTE (CHAR_TO_BYTE (begv) - 1) == '\n')
  3704         return begv;
  3705       begv--;
  3706       limit--;
  3707     }
  3708   return begv;
  3709 }
  3710 
  3711 ptrdiff_t
  3712 get_large_narrowing_zv (ptrdiff_t pos)
  3713 {
  3714   if (long_line_optimizations_region_size <= 0)
  3715     return ZV;
  3716   int len = long_line_optimizations_region_size / 2;
  3717   return min (pos + len, ZV);
  3718 }
  3719 
  3720 static void
  3721 unwind_narrowed_begv (Lisp_Object point_min)
  3722 {
  3723   SET_BUF_BEGV (current_buffer, XFIXNUM (point_min));
  3724 }
  3725 
  3726 /* Set DST to EXPR.  When IT indicates that BEGV should temporarily be
  3727    updated to optimize display, evaluate EXPR with BEGV set to BV.  */
  3728 
  3729 #define SET_WITH_NARROWED_BEGV(IT,DST,EXPR,BV)                          \
  3730   do {                                                                  \
  3731     if (IT->medium_narrowing_begv)                                      \
  3732       {                                                                 \
  3733         specpdl_ref count = SPECPDL_INDEX ();                           \
  3734         record_unwind_protect (unwind_narrowed_begv, Fpoint_min ());    \
  3735         SET_BUF_BEGV (current_buffer, BV);                              \
  3736         DST = EXPR;                                                     \
  3737         unbind_to (count, Qnil);                                        \
  3738       }                                                                 \
  3739     else                                                                \
  3740       DST = EXPR;                                                       \
  3741   } while (0)
  3742 
  3743 /* Initialize IT for the display of window W with window start POS.  */
  3744 
  3745 void
  3746 start_display (struct it *it, struct window *w, struct text_pos pos)
  3747 {
  3748   struct glyph_row *row;
  3749   int first_vpos = window_wants_tab_line (w) + window_wants_header_line (w);
  3750 
  3751   row = w->desired_matrix->rows + first_vpos;
  3752   init_iterator (it, w, CHARPOS (pos), BYTEPOS (pos), row, DEFAULT_FACE_ID);
  3753   it->first_vpos = first_vpos;
  3754 
  3755   /* Don't reseat to previous visible line start if current start
  3756      position is in a string or image.  */
  3757   if (it->method == GET_FROM_BUFFER && it->line_wrap != TRUNCATE)
  3758     {
  3759       int first_y = it->current_y;
  3760 
  3761       /* If window start is not at a line start, skip forward to POS to
  3762          get the correct continuation lines width.  */
  3763       bool start_at_line_beg_p = (CHARPOS (pos) == BEGV
  3764                                   || FETCH_BYTE (BYTEPOS (pos) - 1) == '\n');
  3765       if (!start_at_line_beg_p)
  3766         {
  3767           int new_x;
  3768 
  3769           reseat_at_previous_visible_line_start (it);
  3770           move_it_to (it, CHARPOS (pos), -1, -1, -1, MOVE_TO_POS);
  3771 
  3772           new_x = it->current_x + it->pixel_width;
  3773 
  3774           /* If lines are continued, this line may end in the middle
  3775              of a multi-glyph character (e.g. a control character
  3776              displayed as \003, or in the middle of an overlay
  3777              string).  In this case move_it_to above will not have
  3778              taken us to the start of the continuation line but to the
  3779              end of the continued line.  */
  3780           if (it->current_x > 0
  3781               && it->line_wrap != TRUNCATE /* Lines are continued.  */
  3782               && (/* And glyph doesn't fit on the line.  */
  3783                   new_x > it->last_visible_x
  3784                   /* Or it fits exactly and we're on a window
  3785                      system frame.  */
  3786                   || (new_x == it->last_visible_x
  3787                       && FRAME_WINDOW_P (it->f)
  3788                       && ((it->bidi_p && it->bidi_it.paragraph_dir == R2L)
  3789                           ? WINDOW_LEFT_FRINGE_WIDTH (it->w)
  3790                           : WINDOW_RIGHT_FRINGE_WIDTH (it->w)))))
  3791             {
  3792               if ((it->current.dpvec_index >= 0
  3793                    || it->current.overlay_string_index >= 0)
  3794                   /* If we are on a newline from a display vector or
  3795                      overlay string, then we are already at the end of
  3796                      a screen line; no need to go to the next line in
  3797                      that case, as this line is not really continued.
  3798                      (If we do go to the next line, C-e will not DTRT.)  */
  3799                   && it->c != '\n')
  3800                 {
  3801                   set_iterator_to_next (it, true);
  3802                   move_it_in_display_line_to (it, -1, -1, 0);
  3803                 }
  3804 
  3805               it->continuation_lines_width += it->current_x;
  3806             }
  3807           /* If the character at POS is displayed via a display
  3808              vector, move_it_to above stops at the final glyph of
  3809              IT->dpvec.  To make the caller redisplay that character
  3810              again (a.k.a. start at POS), we need to reset the
  3811              dpvec_index to the beginning of IT->dpvec.  */
  3812           else if (it->current.dpvec_index >= 0)
  3813             it->current.dpvec_index = 0;
  3814 
  3815           /* We're starting a new display line, not affected by the
  3816              height of the continued line, so clear the appropriate
  3817              fields in the iterator structure.  */
  3818           it->max_ascent = it->max_descent = 0;
  3819           it->max_phys_ascent = it->max_phys_descent = 0;
  3820 
  3821           it->current_y = first_y;
  3822           it->vpos = 0;
  3823           it->current_x = it->hpos = 0;
  3824         }
  3825     }
  3826 }
  3827 
  3828 
  3829 /* Return true if POS is a position in ellipses displayed for invisible
  3830    text.  W is the window we display, for text property lookup.  */
  3831 
  3832 static bool
  3833 in_ellipses_for_invisible_text_p (struct display_pos *pos, struct window *w)
  3834 {
  3835   Lisp_Object prop, window;
  3836   bool ellipses_p = false;
  3837   ptrdiff_t charpos = CHARPOS (pos->pos);
  3838 
  3839   /* If POS specifies a position in a display vector, this might
  3840      be for an ellipsis displayed for invisible text.  We won't
  3841      get the iterator set up for delivering that ellipsis unless
  3842      we make sure that it gets aware of the invisible text.  */
  3843   if (pos->dpvec_index >= 0
  3844       && pos->overlay_string_index < 0
  3845       && CHARPOS (pos->string_pos) < 0
  3846       && charpos > BEGV
  3847       && (XSETWINDOW (window, w),
  3848           prop = Fget_char_property (make_fixnum (charpos),
  3849                                      Qinvisible, window),
  3850           TEXT_PROP_MEANS_INVISIBLE (prop) == 0))
  3851     {
  3852       prop = Fget_char_property (make_fixnum (charpos - 1), Qinvisible,
  3853                                  window);
  3854       ellipses_p = 2 == TEXT_PROP_MEANS_INVISIBLE (prop);
  3855     }
  3856 
  3857   return ellipses_p;
  3858 }
  3859 
  3860 
  3861 /* Initialize IT for stepping through current_buffer in window W,
  3862    starting at position POS that includes overlay string and display
  3863    vector/ control character translation position information.  Value
  3864    is false if there are overlay strings with newlines at POS.  */
  3865 
  3866 static bool
  3867 init_from_display_pos (struct it *it, struct window *w, struct display_pos *pos)
  3868 {
  3869   ptrdiff_t charpos = CHARPOS (pos->pos), bytepos = BYTEPOS (pos->pos);
  3870   int i;
  3871   bool overlay_strings_with_newlines = false;
  3872 
  3873   /* If POS specifies a position in a display vector, this might
  3874      be for an ellipsis displayed for invisible text.  We won't
  3875      get the iterator set up for delivering that ellipsis unless
  3876      we make sure that it gets aware of the invisible text.  */
  3877   if (in_ellipses_for_invisible_text_p (pos, w))
  3878     {
  3879       --charpos;
  3880       bytepos = 0;
  3881     }
  3882 
  3883   /* Keep in mind: the call to reseat in init_iterator skips invisible
  3884      text, so we might end up at a position different from POS.  This
  3885      is only a problem when POS is a row start after a newline and an
  3886      overlay starts there with an after-string, and the overlay has an
  3887      invisible property.  Since we don't skip invisible text in
  3888      display_line and elsewhere immediately after consuming the
  3889      newline before the row start, such a POS will not be in a string,
  3890      but the call to init_iterator below will move us to the
  3891      after-string.  */
  3892   init_iterator (it, w, charpos, bytepos, NULL, DEFAULT_FACE_ID);
  3893 
  3894   /* This only scans the current chunk -- it should scan all chunks.
  3895      However, OVERLAY_STRING_CHUNK_SIZE has been increased from 3 in 21.1
  3896      to 16 in 22.1 to make this a lesser problem.  */
  3897   for (i = 0; i < it->n_overlay_strings && i < OVERLAY_STRING_CHUNK_SIZE; ++i)
  3898     {
  3899       const char *s = SSDATA (it->overlay_strings[i]);
  3900       const char *e = s + SBYTES (it->overlay_strings[i]);
  3901 
  3902       while (s < e && *s != '\n')
  3903         ++s;
  3904 
  3905       if (s < e)
  3906         {
  3907           overlay_strings_with_newlines = true;
  3908           break;
  3909         }
  3910     }
  3911 
  3912   /* If position is within an overlay string, set up IT to the right
  3913      overlay string.  */
  3914   if (pos->overlay_string_index >= 0)
  3915     {
  3916       int relative_index;
  3917 
  3918       /* If the first overlay string happens to have a `display'
  3919          property for an image, the iterator will be set up for that
  3920          image, and we have to undo that setup first before we can
  3921          correct the overlay string index.  */
  3922       if (it->method == GET_FROM_IMAGE)
  3923         pop_it (it);
  3924 
  3925       /* We already have the first chunk of overlay strings in
  3926          IT->overlay_strings.  Load more until the one for
  3927          pos->overlay_string_index is in IT->overlay_strings.  */
  3928       if (pos->overlay_string_index >= OVERLAY_STRING_CHUNK_SIZE)
  3929         {
  3930           ptrdiff_t n = pos->overlay_string_index / OVERLAY_STRING_CHUNK_SIZE;
  3931           it->current.overlay_string_index = 0;
  3932           while (n--)
  3933             {
  3934               load_overlay_strings (it, 0);
  3935               it->current.overlay_string_index += OVERLAY_STRING_CHUNK_SIZE;
  3936             }
  3937         }
  3938 
  3939       it->current.overlay_string_index = pos->overlay_string_index;
  3940       relative_index = (it->current.overlay_string_index
  3941                         % OVERLAY_STRING_CHUNK_SIZE);
  3942       it->string = it->overlay_strings[relative_index];
  3943       eassert (STRINGP (it->string));
  3944       it->current.string_pos = pos->string_pos;
  3945       it->method = GET_FROM_STRING;
  3946       it->end_charpos = SCHARS (it->string);
  3947       /* Set up the bidi iterator for this overlay string.  */
  3948       if (it->bidi_p)
  3949         {
  3950           it->bidi_it.string.lstring = it->string;
  3951           it->bidi_it.string.s = NULL;
  3952           it->bidi_it.string.schars = SCHARS (it->string);
  3953           it->bidi_it.string.bufpos = it->overlay_strings_charpos;
  3954           it->bidi_it.string.from_disp_str = it->string_from_display_prop_p;
  3955           it->bidi_it.string.unibyte = !it->multibyte_p;
  3956           it->bidi_it.w = it->w;
  3957           bidi_init_it (IT_STRING_CHARPOS (*it), IT_STRING_BYTEPOS (*it),
  3958                         FRAME_WINDOW_P (it->f), &it->bidi_it);
  3959 
  3960           /* Synchronize the state of the bidi iterator with
  3961              pos->string_pos.  For any string position other than
  3962              zero, this will be done automagically when we resume
  3963              iteration over the string and get_visually_first_element
  3964              is called.  But if string_pos is zero, and the string is
  3965              to be reordered for display, we need to resync manually,
  3966              since it could be that the iteration state recorded in
  3967              pos ended at string_pos of 0 moving backwards in string.  */
  3968           if (CHARPOS (pos->string_pos) == 0)
  3969             {
  3970               get_visually_first_element (it);
  3971               if (IT_STRING_CHARPOS (*it) != 0)
  3972                 do {
  3973                   /* Paranoia.  */
  3974                   eassert (it->bidi_it.charpos < it->bidi_it.string.schars);
  3975                   bidi_move_to_visually_next (&it->bidi_it);
  3976                 } while (it->bidi_it.charpos != 0);
  3977             }
  3978           eassert (IT_STRING_CHARPOS (*it) == it->bidi_it.charpos
  3979                    && IT_STRING_BYTEPOS (*it) == it->bidi_it.bytepos);
  3980         }
  3981     }
  3982 
  3983   if (CHARPOS (pos->string_pos) >= 0)
  3984     {
  3985       /* Recorded position is not in an overlay string, but in another
  3986          string.  This can only be a string from a `display' property.
  3987          IT should already be filled with that string.  */
  3988       it->current.string_pos = pos->string_pos;
  3989       eassert (STRINGP (it->string));
  3990       if (it->bidi_p)
  3991         bidi_init_it (IT_STRING_CHARPOS (*it), IT_STRING_BYTEPOS (*it),
  3992                       FRAME_WINDOW_P (it->f), &it->bidi_it);
  3993     }
  3994 
  3995   /* Restore position in display vector translations, control
  3996      character translations or ellipses.  */
  3997   if (pos->dpvec_index >= 0)
  3998     {
  3999       if (it->dpvec == NULL)
  4000         get_next_display_element (it);
  4001       eassert (it->dpvec && it->current.dpvec_index == 0);
  4002       it->current.dpvec_index = pos->dpvec_index;
  4003     }
  4004 
  4005   CHECK_IT (it);
  4006   return !overlay_strings_with_newlines;
  4007 }
  4008 
  4009 
  4010 /* Initialize IT for stepping through current_buffer in window W
  4011    starting at ROW->start.  */
  4012 
  4013 static void
  4014 init_to_row_start (struct it *it, struct window *w, struct glyph_row *row)
  4015 {
  4016   init_from_display_pos (it, w, &row->start);
  4017   it->start = row->start;
  4018   it->continuation_lines_width = row->continuation_lines_width;
  4019   CHECK_IT (it);
  4020 }
  4021 
  4022 
  4023 /* Initialize IT for stepping through current_buffer in window W
  4024    starting in the line following ROW, i.e. starting at ROW->end.
  4025    Value is false if there are overlay strings with newlines at ROW's
  4026    end position, or if the following row begins with bidi-reordered
  4027    characters that could be composed.  */
  4028 
  4029 static bool
  4030 init_to_row_end (struct it *it, struct window *w, struct glyph_row *row)
  4031 {
  4032   bool success = false;
  4033 
  4034   if (init_from_display_pos (it, w, &row->end))
  4035     {
  4036       if (row->continued_p)
  4037         it->continuation_lines_width
  4038           = row->continuation_lines_width + row->pixel_width;
  4039       CHECK_IT (it);
  4040       /* Initializing IT in the presence of compositions in reordered
  4041          rows is tricky: row->end above will generally cause us to
  4042          start at position that is not the first one in the logical
  4043          order, and we might therefore miss the composition earlier in
  4044          the buffer that affects how glypsh are laid out in this row.
  4045          So we punt instead.  Note: the test below works because
  4046          get_next_display_element calls get_visually_first_element,
  4047          which calls composition_compute_stop_pos, which populates
  4048          it->cmp_it.  */
  4049       if (get_next_display_element (it)
  4050           && (it->bidi_it.scan_dir == -1 && it->cmp_it.id >= 0))
  4051         success = false;
  4052       else
  4053         success = true;
  4054     }
  4055 
  4056   return success;
  4057 }
  4058 
  4059 
  4060 
  4061 
  4062 /***********************************************************************
  4063                            Text properties
  4064  ***********************************************************************/
  4065 
  4066 /* Called when IT reaches IT->stop_charpos.  Handle text property and
  4067    overlay changes.  Set IT->stop_charpos to the next position where
  4068    to stop.  */
  4069 
  4070 static void
  4071 handle_stop (struct it *it)
  4072 {
  4073   enum prop_handled handled;
  4074   bool handle_overlay_change_p;
  4075   struct props *p;
  4076 
  4077   it->dpvec = NULL;
  4078   it->current.dpvec_index = -1;
  4079   handle_overlay_change_p = !it->ignore_overlay_strings_at_pos_p;
  4080   it->ellipsis_p = false;
  4081 
  4082   /* Use face of preceding text for ellipsis (if invisible) */
  4083   if (it->selective_display_ellipsis_p)
  4084     it->saved_face_id = it->face_id;
  4085 
  4086   /* Here's the description of the semantics of, and the logic behind,
  4087      the various HANDLED_* statuses:
  4088 
  4089      HANDLED_NORMALLY means the handler did its job, and the loop
  4090      should proceed to calling the next handler in order.
  4091 
  4092      HANDLED_RECOMPUTE_PROPS means the handler caused a significant
  4093      change in the properties and overlays at current position, so the
  4094      loop should be restarted, to re-invoke the handlers that were
  4095      already called.  This happens when fontification-functions were
  4096      called by handle_fontified_prop, and actually fontified
  4097      something.  Another case where HANDLED_RECOMPUTE_PROPS is
  4098      returned is when we discover overlay strings that need to be
  4099      displayed right away.  The loop below will continue for as long
  4100      as the status is HANDLED_RECOMPUTE_PROPS.
  4101 
  4102      HANDLED_RETURN means return immediately to the caller, to
  4103      continue iteration without calling any further handlers.  This is
  4104      used when we need to act on some property right away, for example
  4105      when we need to display the ellipsis or a replacing display
  4106      property, such as display string or image.
  4107 
  4108      HANDLED_OVERLAY_STRING_CONSUMED means an overlay string was just
  4109      consumed, and the handler switched to the next overlay string.
  4110      This signals the loop below to refrain from looking for more
  4111      overlays before all the overlay strings of the current overlay
  4112      are processed.
  4113 
  4114      Some of the handlers called by the loop push the iterator state
  4115      onto the stack (see 'push_it'), and arrange for the iteration to
  4116      continue with another object, such as an image, a display string,
  4117      or an overlay string.  In most such cases, it->stop_charpos is
  4118      set to the first character of the string, so that when the
  4119      iteration resumes, this function will immediately be called
  4120      again, to examine the properties at the beginning of the string.
  4121 
  4122      When a display or overlay string is exhausted, the iterator state
  4123      is popped (see 'pop_it'), and iteration continues with the
  4124      previous object.  Again, in many such cases this function is
  4125      called again to find the next position where properties might
  4126      change.  */
  4127 
  4128   do
  4129     {
  4130       handled = HANDLED_NORMALLY;
  4131 
  4132       /* Call text property handlers.  */
  4133       for (p = it_props; p->handler; ++p)
  4134         {
  4135           handled = p->handler (it);
  4136 
  4137           if (handled == HANDLED_RECOMPUTE_PROPS)
  4138             break;
  4139           else if (handled == HANDLED_RETURN)
  4140             {
  4141               /* We still want to show before and after strings from
  4142                  overlays even if the actual buffer text is replaced.  */
  4143               if (!handle_overlay_change_p
  4144                   || it->sp > 1
  4145                   /* Don't call get_overlay_strings_1 if we already
  4146                      have overlay strings loaded, because doing so
  4147                      will load them again and push the iterator state
  4148                      onto the stack one more time, which is not
  4149                      expected by the rest of the code that processes
  4150                      overlay strings.  */
  4151                   || (it->current.overlay_string_index < 0
  4152                       && !get_overlay_strings_1 (it, 0, false)))
  4153                 {
  4154                   if (it->ellipsis_p)
  4155                     setup_for_ellipsis (it, 0);
  4156                   /* When handling a display spec, we might load an
  4157                      empty string.  In that case, discard it here.  We
  4158                      used to discard it in handle_single_display_spec,
  4159                      but that causes get_overlay_strings_1, above, to
  4160                      ignore overlay strings that we must check.  */
  4161                   if (STRINGP (it->string) && !SCHARS (it->string))
  4162                     pop_it (it);
  4163                   return;
  4164                 }
  4165               else if (STRINGP (it->string) && !SCHARS (it->string))
  4166                 pop_it (it);
  4167               else
  4168                 {
  4169                   it->string_from_display_prop_p = false;
  4170                   it->from_disp_prop_p = false;
  4171                   handle_overlay_change_p = false;
  4172                 }
  4173               handled = HANDLED_RECOMPUTE_PROPS;
  4174               break;
  4175             }
  4176           else if (handled == HANDLED_OVERLAY_STRING_CONSUMED)
  4177             handle_overlay_change_p = false;
  4178         }
  4179 
  4180       if (handled != HANDLED_RECOMPUTE_PROPS)
  4181         {
  4182           /* Don't check for overlay strings below when set to deliver
  4183              characters from a display vector.  */
  4184           if (it->method == GET_FROM_DISPLAY_VECTOR)
  4185             handle_overlay_change_p = false;
  4186 
  4187           /* Handle overlay changes.
  4188              This sets HANDLED to HANDLED_RECOMPUTE_PROPS
  4189              if it finds overlays.  */
  4190           if (handle_overlay_change_p)
  4191             handled = handle_overlay_change (it);
  4192         }
  4193 
  4194       if (it->ellipsis_p)
  4195         {
  4196           setup_for_ellipsis (it, 0);
  4197           break;
  4198         }
  4199     }
  4200   while (handled == HANDLED_RECOMPUTE_PROPS);
  4201 
  4202   /* Determine where to stop next.  */
  4203   if (handled == HANDLED_NORMALLY)
  4204     compute_stop_pos (it);
  4205 }
  4206 
  4207 
  4208 /* Compute IT->stop_charpos from text property and overlay change
  4209    information for IT's current position.  */
  4210 
  4211 static void
  4212 compute_stop_pos (struct it *it)
  4213 {
  4214   register INTERVAL iv, next_iv;
  4215   Lisp_Object object, limit, position;
  4216   ptrdiff_t charpos, bytepos, cmp_limit_pos = -1;
  4217 
  4218   if (STRINGP (it->string))
  4219     {
  4220       /* Strings are usually short, so don't limit the search for
  4221          properties.  */
  4222       it->stop_charpos = it->end_charpos;
  4223       object = it->string;
  4224       limit = Qnil;
  4225       charpos = IT_STRING_CHARPOS (*it);
  4226       bytepos = IT_STRING_BYTEPOS (*it);
  4227     }
  4228   else
  4229     {
  4230       ptrdiff_t pos;
  4231 
  4232       /* If end_charpos is out of range for some reason, such as a
  4233          misbehaving display function, rationalize it (Bug#5984).  */
  4234       if (it->end_charpos > ZV)
  4235         it->end_charpos = ZV;
  4236       it->stop_charpos = it->end_charpos;
  4237 
  4238       /* If next overlay change is in front of the current stop pos
  4239          (which is IT->end_charpos), stop there.  Note: value of
  4240          next_overlay_change is point-max if no overlay change
  4241          follows.  */
  4242       charpos = IT_CHARPOS (*it);
  4243       bytepos = IT_BYTEPOS (*it);
  4244       pos = next_overlay_change (charpos);
  4245       if (pos < it->stop_charpos)
  4246         it->stop_charpos = pos;
  4247       /* If we are breaking compositions at point, stop at point.  */
  4248       if (!NILP (BVAR (current_buffer, enable_multibyte_characters))
  4249           && !NILP (Vauto_composition_mode)
  4250           && composition_break_at_point
  4251           && charpos < PT && PT < it->stop_charpos)
  4252         it->stop_charpos = PT;
  4253 
  4254       /* Set up variables for computing the stop position from text
  4255          property changes.  */
  4256       XSETBUFFER (object, current_buffer);
  4257       pos = charpos + TEXT_PROP_DISTANCE_LIMIT;
  4258       /* Make sure the above arbitrary limit position is not in the
  4259          middle of composable text, so we don't break compositions by
  4260          submitting the composable text to the shaper in separate
  4261          chunks.  We play safe here by assuming that only SPC, TAB,
  4262          FF, and NL cannot be in some composition; in particular, most
  4263          ASCII punctuation characters could be composed into ligatures.  */
  4264       if (!composition_break_at_point
  4265           && !NILP (BVAR (current_buffer, enable_multibyte_characters))
  4266           && !NILP (Vauto_composition_mode))
  4267         {
  4268           ptrdiff_t endpos = charpos + 10 * TEXT_PROP_DISTANCE_LIMIT;
  4269           bool found = false;
  4270 
  4271           if (pos > ZV)
  4272             pos = ZV;
  4273           if (endpos > ZV)
  4274             endpos = ZV;
  4275           ptrdiff_t bpos = CHAR_TO_BYTE (pos);
  4276           while (pos < endpos)
  4277             {
  4278               int ch = fetch_char_advance_no_check (&pos, &bpos);
  4279               if (ch == ' ' || ch == '\t' || ch == '\n' || ch == '\f')
  4280                 {
  4281                   found = true;
  4282                   break;
  4283                 }
  4284             }
  4285           if (found)
  4286             {
  4287               pos--;
  4288               cmp_limit_pos = pos;
  4289             }
  4290           else if (it->stop_charpos < endpos)
  4291             pos = it->stop_charpos;
  4292           else
  4293             {
  4294               /* Give up and use the original arbitrary limit.  */
  4295               pos = charpos + TEXT_PROP_DISTANCE_LIMIT;
  4296             }
  4297         }
  4298       limit = make_fixnum (pos);
  4299     }
  4300 
  4301   /* Get the interval containing IT's position.  Value is a null
  4302      interval if there isn't such an interval.  */
  4303   position = make_fixnum (charpos);
  4304   iv = validate_interval_range (object, &position, &position, false);
  4305   if (iv)
  4306     {
  4307       Lisp_Object values_here[LAST_PROP_IDX];
  4308       struct props *p;
  4309 
  4310       /* Get properties here.  */
  4311       for (p = it_props; p->handler; ++p)
  4312         values_here[p->idx] = textget (iv->plist,
  4313                                        builtin_lisp_symbol (p->name));
  4314 
  4315       /* Look for an interval following iv that has different
  4316          properties.  */
  4317       for (next_iv = next_interval (iv);
  4318            (next_iv
  4319             && (NILP (limit)
  4320                 || XFIXNAT (limit) > next_iv->position));
  4321            next_iv = next_interval (next_iv))
  4322         {
  4323           for (p = it_props; p->handler; ++p)
  4324             {
  4325               Lisp_Object new_value = textget (next_iv->plist,
  4326                                                builtin_lisp_symbol (p->name));
  4327               if (!EQ (values_here[p->idx], new_value))
  4328                 break;
  4329             }
  4330 
  4331           if (p->handler)
  4332             break;
  4333         }
  4334 
  4335       if (next_iv)
  4336         {
  4337           if (FIXNUMP (limit)
  4338               && next_iv->position >= XFIXNAT (limit))
  4339             /* No text property change up to limit.  */
  4340             it->stop_charpos = min (XFIXNAT (limit), it->stop_charpos);
  4341           else
  4342             /* Text properties change in next_iv.  */
  4343             it->stop_charpos = min (it->stop_charpos, next_iv->position);
  4344         }
  4345     }
  4346 
  4347   if (it->cmp_it.id < 0
  4348       && (STRINGP (it->string)
  4349           || ((!it->bidi_p || it->bidi_it.scan_dir >= 0)
  4350               && it->cmp_it.stop_pos <= IT_CHARPOS (*it))))
  4351     {
  4352       ptrdiff_t stoppos = it->end_charpos;
  4353 
  4354       /* If we found, above, a buffer position that cannot be part of
  4355          an automatic composition, limit the search of composable
  4356          characters to that position.  */
  4357       if (it->bidi_p && it->bidi_it.scan_dir < 0)
  4358         stoppos = -1;
  4359       else if (cmp_limit_pos > 0)
  4360         stoppos = cmp_limit_pos;
  4361       /* Force composition_compute_stop_pos avoid the costly search
  4362          for static compositions, since those were already found by
  4363          looking at text properties, above.  */
  4364       composition_compute_stop_pos (&it->cmp_it, charpos, bytepos,
  4365                                     stoppos, it->string, false);
  4366     }
  4367 
  4368   eassert (STRINGP (it->string)
  4369            || (it->stop_charpos >= BEGV
  4370                && it->stop_charpos >= IT_CHARPOS (*it)));
  4371 }
  4372 
  4373 /* How many characters forward to search for a display property or
  4374    display string.  Searching too far forward makes the bidi display
  4375    sluggish, especially in small windows.  */
  4376 #define MAX_DISP_SCAN 250
  4377 
  4378 /* Return the character position of a display string at or after
  4379    position specified by POSITION.  If no display string exists at or
  4380    after POSITION, return ZV.  A display string is either an overlay
  4381    with `display' property whose value is a string, or a `display'
  4382    text property whose value is a string.  STRING is data about the
  4383    string to iterate; if STRING->lstring is nil, we are iterating a
  4384    buffer.  FRAME_WINDOW_P is true when we are displaying a window
  4385    on a GUI frame.  DISP_PROP is set to zero if we searched
  4386    MAX_DISP_SCAN characters forward without finding any display
  4387    strings, non-zero otherwise.  It is set to 2 if the display string
  4388    uses any kind of `(space ...)' spec that will produce a stretch of
  4389    white space in the text area.  */
  4390 ptrdiff_t
  4391 compute_display_string_pos (struct text_pos *position,
  4392                             struct bidi_string_data *string,
  4393                             struct window *w,
  4394                             bool frame_window_p, int *disp_prop)
  4395 {
  4396   /* OBJECT = nil means current buffer.  */
  4397   Lisp_Object object, object1;
  4398   Lisp_Object pos, spec, limpos;
  4399   bool string_p = string && (STRINGP (string->lstring) || string->s);
  4400   ptrdiff_t eob = string_p ? string->schars : ZV;
  4401   ptrdiff_t begb = string_p ? 0 : BEGV;
  4402   ptrdiff_t bufpos, charpos = CHARPOS (*position);
  4403   ptrdiff_t lim =
  4404     (charpos < eob - MAX_DISP_SCAN) ? charpos + MAX_DISP_SCAN : eob;
  4405   struct text_pos tpos;
  4406   int rv = 0;
  4407 
  4408   if (string && STRINGP (string->lstring))
  4409     object1 = object = string->lstring;
  4410   else if (w && !string_p)
  4411     {
  4412       XSETWINDOW (object, w);
  4413       object1 = Qnil;
  4414     }
  4415   else
  4416     object1 = object = Qnil;
  4417 
  4418   *disp_prop = 1;
  4419 
  4420   if (charpos >= eob
  4421       /* We don't support display properties whose values are strings
  4422          that have display string properties.  */
  4423       || string->from_disp_str
  4424       /* C strings cannot have display properties.  */
  4425       || (string->s && !STRINGP (object)))
  4426     {
  4427       *disp_prop = 0;
  4428       return eob;
  4429     }
  4430 
  4431   /* If the character at CHARPOS is where the display string begins,
  4432      return CHARPOS.  */
  4433   pos = make_fixnum (charpos);
  4434   if (STRINGP (object))
  4435     bufpos = string->bufpos;
  4436   else
  4437     bufpos = charpos;
  4438   tpos = *position;
  4439   if (!NILP (spec = Fget_char_property (pos, Qdisplay, object))
  4440       && (charpos <= begb
  4441           || !EQ (Fget_char_property (make_fixnum (charpos - 1), Qdisplay,
  4442                                       object),
  4443                   spec))
  4444       && (rv = handle_display_spec (NULL, spec, object1, Qnil, &tpos, bufpos,
  4445                                     frame_window_p)))
  4446     {
  4447       if (rv == 2)
  4448         *disp_prop = 2;
  4449       return charpos;
  4450     }
  4451 
  4452   /* Look forward for the first character with a `display' property
  4453      that will replace the underlying text when displayed.  */
  4454   limpos = make_fixnum (lim);
  4455   do {
  4456     pos = Fnext_single_char_property_change (pos, Qdisplay, object1, limpos);
  4457     CHARPOS (tpos) = XFIXNAT (pos);
  4458     if (CHARPOS (tpos) >= lim)
  4459       {
  4460         *disp_prop = 0;
  4461         break;
  4462       }
  4463     if (STRINGP (object))
  4464       BYTEPOS (tpos) = string_char_to_byte (object, CHARPOS (tpos));
  4465     else
  4466       BYTEPOS (tpos) = CHAR_TO_BYTE (CHARPOS (tpos));
  4467     spec = Fget_char_property (pos, Qdisplay, object);
  4468     if (!STRINGP (object))
  4469       bufpos = CHARPOS (tpos);
  4470   } while (NILP (spec)
  4471            || !(rv = handle_display_spec (NULL, spec, object1, Qnil, &tpos,
  4472                                           bufpos, frame_window_p)));
  4473   if (rv == 2)
  4474     *disp_prop = 2;
  4475 
  4476   return CHARPOS (tpos);
  4477 }
  4478 
  4479 /* Return the character position of the end of the display string that
  4480    started at CHARPOS.  If there's no display string at CHARPOS,
  4481    return -1.  A display string is either an overlay with `display'
  4482    property whose value is a string or a `display' text property whose
  4483    value is a string.  */
  4484 ptrdiff_t
  4485 compute_display_string_end (ptrdiff_t charpos, struct bidi_string_data *string)
  4486 {
  4487   /* OBJECT = nil means current buffer.  */
  4488   Lisp_Object object =
  4489     (string && STRINGP (string->lstring)) ? string->lstring : Qnil;
  4490   Lisp_Object pos = make_fixnum (charpos);
  4491   ptrdiff_t eob =
  4492     (STRINGP (object) || (string && string->s)) ? string->schars : ZV;
  4493 
  4494   if (charpos >= eob || (string->s && !STRINGP (object)))
  4495     return eob;
  4496 
  4497   /* It could happen that the display property or overlay was removed
  4498      since we found it in compute_display_string_pos above.  One way
  4499      this can happen is if JIT font-lock was called (through
  4500      handle_fontified_prop), and jit-lock-functions remove text
  4501      properties or overlays from the portion of buffer that includes
  4502      CHARPOS.  Muse mode is known to do that, for example.  In this
  4503      case, we return -1 to the caller, to signal that no display
  4504      string is actually present at CHARPOS.  See bidi_fetch_char for
  4505      how this is handled.
  4506 
  4507      An alternative would be to never look for display properties past
  4508      it->stop_charpos.  But neither compute_display_string_pos nor
  4509      bidi_fetch_char that calls it know or care where the next
  4510      stop_charpos is.  */
  4511   if (NILP (Fget_char_property (pos, Qdisplay, object)))
  4512     return -1;
  4513 
  4514   /* Look forward for the first character where the `display' property
  4515      changes.  */
  4516   pos = Fnext_single_char_property_change (pos, Qdisplay, object, Qnil);
  4517 
  4518   return XFIXNAT (pos);
  4519 }
  4520 
  4521 
  4522 
  4523 /***********************************************************************
  4524                             Fontification
  4525  ***********************************************************************/
  4526 
  4527 /* Handle changes in the `fontified' property of the current buffer by
  4528    calling hook functions from Qfontification_functions to fontify
  4529    regions of text.  */
  4530 
  4531 static enum prop_handled
  4532 handle_fontified_prop (struct it *it)
  4533 {
  4534   Lisp_Object prop, pos;
  4535   enum prop_handled handled = HANDLED_NORMALLY;
  4536 
  4537   if (!NILP (Vmemory_full))
  4538     return handled;
  4539 
  4540   /* Get the value of the `fontified' property at IT's current buffer
  4541      position.  (The `fontified' property doesn't have a special
  4542      meaning in strings.)  If the value is nil, call functions from
  4543      Qfontification_functions.  */
  4544   if (!STRINGP (it->string)
  4545       && it->s == NULL
  4546       && !NILP (Vfontification_functions)
  4547       && !(input_was_pending && redisplay_skip_fontification_on_input)
  4548       && !NILP (Vrun_hooks)
  4549       && (pos = make_fixnum (IT_CHARPOS (*it)),
  4550           prop = Fget_char_property (pos, Qfontified, Qnil),
  4551           /* Ignore the special cased nil value always present at EOB since
  4552              no amount of fontifying will be able to change it.  */
  4553           NILP (prop) && IT_CHARPOS (*it) < Z))
  4554     {
  4555       specpdl_ref count = SPECPDL_INDEX ();
  4556       Lisp_Object val;
  4557       struct buffer *obuf = current_buffer;
  4558       ptrdiff_t begv = BEGV, zv = ZV;
  4559       bool old_clip_changed = current_buffer->clip_changed;
  4560       bool saved_inhibit_flag = it->f->inhibit_clear_image_cache;
  4561 
  4562       val = Vfontification_functions;
  4563       specbind (Qfontification_functions, Qnil);
  4564 
  4565       eassert (it->end_charpos == ZV);
  4566 
  4567       if (current_buffer->long_line_optimizations_p
  4568           && long_line_optimizations_region_size > 0)
  4569         {
  4570           ptrdiff_t begv = it->large_narrowing_begv;
  4571           ptrdiff_t zv = it->large_narrowing_zv;
  4572           ptrdiff_t charpos = IT_CHARPOS (*it);
  4573           if (charpos < begv || charpos > zv)
  4574             {
  4575               begv = get_large_narrowing_begv (charpos);
  4576               zv = get_large_narrowing_zv (charpos);
  4577             }
  4578           if (begv != BEG || zv != Z)
  4579             labeled_narrow_to_region (make_fixnum (begv), make_fixnum (zv),
  4580                                       Qlong_line_optimizations_in_fontification_functions);
  4581         }
  4582 
  4583       /* Don't allow Lisp that runs from 'fontification-functions'
  4584          clear our face and image caches behind our back.  */
  4585       it->f->inhibit_clear_image_cache = true;
  4586 
  4587       if (!CONSP (val) || EQ (XCAR (val), Qlambda))
  4588         safe_call1 (val, pos);
  4589       else
  4590         {
  4591           Lisp_Object fns, fn;
  4592 
  4593           fns = Qnil;
  4594 
  4595           for (; CONSP (val); val = XCDR (val))
  4596             {
  4597               fn = XCAR (val);
  4598 
  4599               if (EQ (fn, Qt))
  4600                 {
  4601                   /* A value of t indicates this hook has a local
  4602                      binding; it means to run the global binding too.
  4603                      In a global value, t should not occur.  If it
  4604                      does, we must ignore it to avoid an endless
  4605                      loop.  */
  4606                   for (fns = Fdefault_value (Qfontification_functions);
  4607                        CONSP (fns);
  4608                        fns = XCDR (fns))
  4609                     {
  4610                       fn = XCAR (fns);
  4611                       if (!EQ (fn, Qt))
  4612                         safe_call1 (fn, pos);
  4613                     }
  4614                 }
  4615               else
  4616                 safe_call1 (fn, pos);
  4617             }
  4618         }
  4619 
  4620       it->f->inhibit_clear_image_cache = saved_inhibit_flag;
  4621       unbind_to (count, Qnil);
  4622 
  4623       /* Fontification functions routinely call `save-restriction'.
  4624          Normally, this tags clip_changed, which can confuse redisplay
  4625          (see discussion in Bug#6671).  Since we don't perform any
  4626          special handling of fontification changes in the case where
  4627          `save-restriction' isn't called, there's no point doing so in
  4628          this case either.  So, if the buffer's restrictions are
  4629          actually left unchanged, reset clip_changed.  */
  4630       if (obuf == current_buffer)
  4631         {
  4632           if (begv == BEGV && zv == ZV)
  4633             current_buffer->clip_changed = old_clip_changed;
  4634         }
  4635       /* There isn't much we can reasonably do to protect against
  4636          misbehaving fontification, but here's a fig leaf.  */
  4637       else if (BUFFER_LIVE_P (obuf))
  4638         set_buffer_internal_1 (obuf);
  4639 
  4640       /* The fontification code may have added/removed text.
  4641          It could do even a lot worse, but let's at least protect against
  4642          the most obvious case where only the text past `pos' gets changed',
  4643          as is/was done in grep.el where some escapes sequences are turned
  4644          into face properties (bug#7876).  */
  4645       it->end_charpos = ZV;
  4646 
  4647       /* Return HANDLED_RECOMPUTE_PROPS only if function fontified
  4648          something.  This avoids an endless loop if they failed to
  4649          fontify the text for which reason ever.  */
  4650       if (!NILP (Fget_char_property (pos, Qfontified, Qnil)))
  4651         handled = HANDLED_RECOMPUTE_PROPS;
  4652     }
  4653 
  4654   return handled;
  4655 }
  4656 
  4657 
  4658 
  4659 /***********************************************************************
  4660                                 Faces
  4661  ***********************************************************************/
  4662 
  4663 static int
  4664 face_at_pos (const struct it *it, enum lface_attribute_index attr_filter)
  4665 {
  4666   ptrdiff_t next_stop;
  4667 
  4668   if (!STRINGP (it->string))
  4669     {
  4670       return face_at_buffer_position (it->w,
  4671                                       IT_CHARPOS (*it),
  4672                                       &next_stop,
  4673                                       (IT_CHARPOS (*it)
  4674                                        + TEXT_PROP_DISTANCE_LIMIT),
  4675                                       false, it->base_face_id,
  4676                                       attr_filter);
  4677     }
  4678   else
  4679     {
  4680       int base_face_id;
  4681       ptrdiff_t bufpos;
  4682       int i;
  4683       Lisp_Object from_overlay
  4684         = (it->current.overlay_string_index >= 0
  4685            ? it->string_overlays[it->current.overlay_string_index
  4686                                  % OVERLAY_STRING_CHUNK_SIZE]
  4687            : Qnil);
  4688 
  4689       /* See if we got to this string directly or indirectly from
  4690          an overlay property.  That includes the before-string or
  4691          after-string of an overlay, strings in display properties
  4692          provided by an overlay, their text properties, etc.
  4693 
  4694          FROM_OVERLAY is the overlay that brought us here, or nil if none.  */
  4695       if (! NILP (from_overlay))
  4696         for (i = it->sp - 1; i >= 0; i--)
  4697           {
  4698             if (it->stack[i].current.overlay_string_index >= 0)
  4699               from_overlay
  4700                 = it->string_overlays[it->stack[i].current.overlay_string_index
  4701                                       % OVERLAY_STRING_CHUNK_SIZE];
  4702             else if (! NILP (it->stack[i].from_overlay))
  4703               from_overlay = it->stack[i].from_overlay;
  4704 
  4705             if (!NILP (from_overlay))
  4706               break;
  4707           }
  4708 
  4709       if (! NILP (from_overlay))
  4710         {
  4711           bufpos = IT_CHARPOS (*it);
  4712           /* For a string from an overlay, the base face depends
  4713              only on text properties and ignores overlays.  */
  4714           base_face_id
  4715             = face_for_overlay_string (it->w,
  4716                                        IT_CHARPOS (*it),
  4717                                        &next_stop,
  4718                                        (IT_CHARPOS (*it)
  4719                                         + TEXT_PROP_DISTANCE_LIMIT),
  4720                                        false,
  4721                                        from_overlay, attr_filter);
  4722         }
  4723       else
  4724         {
  4725           bufpos = 0;
  4726 
  4727           /* For strings from a `display' property, use the face at
  4728              IT's current buffer position as the base face to merge
  4729              with, so that overlay strings appear in the same face as
  4730              surrounding text, unless they specify their own faces.
  4731              For strings from wrap-prefix and line-prefix properties,
  4732              use the default face, possibly remapped via
  4733              Vface_remapping_alist.  */
  4734           /* Note that the fact that we use the face at _buffer_
  4735              position means that a 'display' property on an overlay
  4736              string will not inherit the face of that overlay string,
  4737              but will instead revert to the face of buffer text
  4738              covered by the overlay.  This is visible, e.g., when the
  4739              overlay specifies a box face, but neither the buffer nor
  4740              the display string do.  This sounds like a design bug,
  4741              but Emacs always did that since v21.1, so changing that
  4742              might be a big deal.  */
  4743           base_face_id = it->string_from_prefix_prop_p
  4744             ? (!NILP (Vface_remapping_alist)
  4745                ? lookup_basic_face (it->w, it->f, DEFAULT_FACE_ID)
  4746                : DEFAULT_FACE_ID)
  4747             : underlying_face_id (it);
  4748         }
  4749 
  4750       return face_at_string_position (it->w,
  4751                                       it->string,
  4752                                       IT_STRING_CHARPOS (*it),
  4753                                       bufpos,
  4754                                       &next_stop,
  4755                                       base_face_id, false,
  4756                                       attr_filter);
  4757     } /* !STRINGP (it->string) */
  4758 }
  4759 
  4760 
  4761 /* Set up iterator IT from face properties at its current position.
  4762    Called from handle_stop.  */
  4763 static enum prop_handled
  4764 handle_face_prop (struct it *it)
  4765 {
  4766   specpdl_ref count = SPECPDL_INDEX ();
  4767   /* Don't allow the user to quit out of face-merging code, in case
  4768      this is called when redisplaying a non-selected window, with
  4769      point temporarily moved to window-point.  */
  4770   specbind (Qinhibit_quit, Qt);
  4771   const int new_face_id = face_at_pos (it, 0);
  4772   unbind_to (count, Qnil);
  4773 
  4774 
  4775   /* Is this a start of a run of characters with box face?
  4776      Caveat: this can be called for a freshly initialized
  4777      iterator; face_id is -1 in this case.  We know that the new
  4778      face will not change until limit, i.e. if the new face has a
  4779      box, all characters up to limit will have one.  But, as
  4780      usual, we don't know whether limit is really the end.  */
  4781   if (new_face_id != it->face_id)
  4782     {
  4783       struct face *new_face = FACE_FROM_ID (it->f, new_face_id);
  4784       /* If it->face_id is -1, old_face below will be NULL, see
  4785          the definition of FACE_FROM_ID_OR_NULL.  This will happen
  4786          if this is the initial call that gets the face.  */
  4787       struct face *old_face = FACE_FROM_ID_OR_NULL (it->f, it->face_id);
  4788 
  4789       /* If the value of face_id of the iterator is -1, we have to
  4790          look in front of IT's position and see whether there is a
  4791          face there that's different from new_face_id.  */
  4792       if (!STRINGP (it->string)
  4793           && !old_face
  4794           && IT_CHARPOS (*it) > BEG)
  4795         {
  4796           const int prev_face_id = face_before_it_pos (it);
  4797 
  4798           old_face = FACE_FROM_ID_OR_NULL (it->f, prev_face_id);
  4799         }
  4800 
  4801       /* If the new face has a box, but the old face does not,
  4802          this is the start of a run of characters with box face,
  4803          i.e. this character has a shadow on the left side.  */
  4804       it->face_id = new_face_id;
  4805       /* Don't reset the start_of_box_run_p flag, only set it if
  4806          needed.  */
  4807       if (!(it->start_of_box_run_p && old_face && old_face->box))
  4808         it->start_of_box_run_p = (new_face->box != FACE_NO_BOX
  4809                                   && (old_face == NULL || !old_face->box));
  4810       it->face_box_p = new_face->box != FACE_NO_BOX;
  4811     }
  4812 
  4813   return HANDLED_NORMALLY;
  4814 }
  4815 
  4816 
  4817 /* Return the ID of the face ``underlying'' IT's current position,
  4818    which is in a string.  If the iterator is associated with a
  4819    buffer, return the face at IT's current buffer position.
  4820    Otherwise, use the iterator's base_face_id.  */
  4821 
  4822 static int
  4823 underlying_face_id (const struct it *it)
  4824 {
  4825   int face_id = it->base_face_id, i;
  4826 
  4827   eassert (STRINGP (it->string));
  4828 
  4829   for (i = it->sp - 1; i >= 0; --i)
  4830     if (NILP (it->stack[i].string))
  4831       face_id = it->stack[i].face_id;
  4832 
  4833   return face_id;
  4834 }
  4835 
  4836 
  4837 /* Compute the face one character before or after the current position
  4838    of IT, in the visual order.  BEFORE_P means get the face
  4839    in front (to the left in L2R paragraphs, to the right in R2L
  4840    paragraphs) of IT's screen position.  Value is the ID of the face.  */
  4841 
  4842 static int
  4843 face_before_or_after_it_pos (struct it *it, bool before_p)
  4844 {
  4845   int face_id, limit;
  4846   ptrdiff_t next_check_charpos;
  4847   struct it it_copy;
  4848   void *it_copy_data = NULL;
  4849 
  4850   eassert (it->s == NULL);
  4851 
  4852   if (STRINGP (it->string))
  4853     {
  4854       ptrdiff_t bufpos, charpos;
  4855       int base_face_id;
  4856 
  4857       /* No face change past the end of the string (for the case we
  4858          are padding with spaces).  No face change before the string
  4859          start.  Ignore face changes before the first visible
  4860          character on this display line.  */
  4861       if (IT_STRING_CHARPOS (*it) >= SCHARS (it->string)
  4862           || (IT_STRING_CHARPOS (*it) == 0 && before_p)
  4863           || it->current_x <= it->first_visible_x)
  4864         return it->face_id;
  4865 
  4866       if (!it->bidi_p)
  4867         {
  4868           /* Set charpos to the position before or after IT's current
  4869              position, in the logical order, which in the non-bidi
  4870              case is the same as the visual order.  */
  4871           if (before_p)
  4872             charpos = IT_STRING_CHARPOS (*it) - 1;
  4873           else if (it->what == IT_COMPOSITION)
  4874             /* For composition, we must check the character after the
  4875                composition.  */
  4876             charpos = IT_STRING_CHARPOS (*it) + it->cmp_it.nchars;
  4877           else
  4878             charpos = IT_STRING_CHARPOS (*it) + 1;
  4879         }
  4880       else
  4881         {
  4882           /* With bidi iteration, the character before the current in
  4883              the visual order cannot be found by simple iteration,
  4884              because "reverse" reordering is not supported.  Instead,
  4885              we need to start from the string beginning and go all the
  4886              way to the current string position, remembering the
  4887              visually-previous position.  We need to start from the
  4888              string beginning for the character after the current as
  4889              well, since the iterator state in IT may have been
  4890              pushed, and the bidi cache is no longer coherent with the
  4891              string's text.  */
  4892           SAVE_IT (it_copy, *it, it_copy_data);
  4893           IT_STRING_CHARPOS (it_copy) = 0;
  4894           bidi_init_it (0, 0, FRAME_WINDOW_P (it_copy.f), &it_copy.bidi_it);
  4895           it_copy.bidi_it.scan_dir = 0;
  4896 
  4897           do
  4898             {
  4899               charpos = it_copy.bidi_it.charpos;
  4900               if (charpos >= SCHARS (it->string))
  4901                 break;
  4902               bidi_move_to_visually_next (&it_copy.bidi_it);
  4903             }
  4904           while (it_copy.bidi_it.charpos != IT_STRING_CHARPOS (*it));
  4905 
  4906           if (!before_p)
  4907             {
  4908               /* Set charpos to the string position of the character
  4909                  that comes after IT's current position in the visual
  4910                  order.  */
  4911               int n = (it->what == IT_COMPOSITION ? it->cmp_it.nchars : 1);
  4912               /* If this is the first string character,
  4913                  bidi_move_to_visually_next will deliver character at
  4914                  current position without moving, so we need to enlarge N.  */
  4915               if (it_copy.bidi_it.first_elt)
  4916                 n++;
  4917               while (n--)
  4918                 bidi_move_to_visually_next (&it_copy.bidi_it);
  4919 
  4920               charpos = it_copy.bidi_it.charpos;
  4921             }
  4922 
  4923           RESTORE_IT (it, it, it_copy_data);
  4924         }
  4925       eassert (0 <= charpos && charpos <= SCHARS (it->string));
  4926 
  4927       if (it->current.overlay_string_index >= 0)
  4928         bufpos = IT_CHARPOS (*it);
  4929       else
  4930         bufpos = 0;
  4931 
  4932       base_face_id = underlying_face_id (it);
  4933 
  4934       /* Get the face for ASCII, or unibyte.  */
  4935       face_id = face_at_string_position (it->w, it->string, charpos,
  4936                                          bufpos, &next_check_charpos,
  4937                                          base_face_id, false, 0);
  4938 
  4939       /* Correct the face for charsets different from ASCII.  Do it
  4940          for the multibyte case only.  The face returned above is
  4941          suitable for unibyte text if IT->string is unibyte.  */
  4942       if (STRING_MULTIBYTE (it->string))
  4943         {
  4944           struct text_pos pos1 = string_pos (charpos, it->string);
  4945           const unsigned char *p = SDATA (it->string) + BYTEPOS (pos1);
  4946           struct face *face = FACE_FROM_ID (it->f, face_id);
  4947           int len, c = check_char_and_length (p, &len);
  4948           face_id = FACE_FOR_CHAR (it->f, face, c, charpos, it->string);
  4949         }
  4950     }
  4951   else
  4952     {
  4953       struct text_pos pos;
  4954 
  4955       if ((IT_CHARPOS (*it) >= ZV && !before_p)
  4956           || (IT_CHARPOS (*it) <= BEGV && before_p))
  4957         return it->face_id;
  4958 
  4959       limit = IT_CHARPOS (*it) + TEXT_PROP_DISTANCE_LIMIT;
  4960       pos = it->current.pos;
  4961 
  4962       if (!it->bidi_p)
  4963         {
  4964           if (before_p)
  4965             DEC_TEXT_POS (pos, it->multibyte_p);
  4966           else
  4967             {
  4968               if (it->what == IT_COMPOSITION)
  4969                 {
  4970                   /* For composition, we must check the position after
  4971                      the composition.  */
  4972                   pos.charpos += it->cmp_it.nchars;
  4973                   pos.bytepos += it->len;
  4974                 }
  4975               else
  4976                 INC_TEXT_POS (pos, it->multibyte_p);
  4977             }
  4978         }
  4979       else
  4980         {
  4981           if (before_p)
  4982             {
  4983               int current_x;
  4984 
  4985               /* With bidi iteration, the character before the current
  4986                  in the visual order cannot be found by simple
  4987                  iteration, because "reverse" reordering is not
  4988                  supported.  Instead, we need to use the move_it_*
  4989                  family of functions, and move to the previous
  4990                  character starting from the beginning of the visual
  4991                  line.  */
  4992               /* Ignore face changes before the first visible
  4993                  character on this display line.  */
  4994               if (it->current_x <= it->first_visible_x)
  4995                 return it->face_id;
  4996               SAVE_IT (it_copy, *it, it_copy_data);
  4997               /* Implementation note: Since move_it_in_display_line
  4998                  works in the iterator geometry, and thinks the first
  4999                  character is always the leftmost, even in R2L lines,
  5000                  we don't need to distinguish between the R2L and L2R
  5001                  cases here.  */
  5002               current_x = it_copy.current_x;
  5003               move_it_vertically_backward (&it_copy, 0);
  5004               move_it_in_display_line (&it_copy, ZV, current_x - 1, MOVE_TO_X);
  5005               pos = it_copy.current.pos;
  5006               RESTORE_IT (it, it, it_copy_data);
  5007             }
  5008           else
  5009             {
  5010               /* Set charpos to the buffer position of the character
  5011                  that comes after IT's current position in the visual
  5012                  order.  */
  5013               int n = (it->what == IT_COMPOSITION ? it->cmp_it.nchars : 1);
  5014 
  5015               it_copy = *it;
  5016               /* If this is the first display element,
  5017                  bidi_move_to_visually_next will deliver character at
  5018                  current position without moving, so we need to enlarge N.  */
  5019               if (it->bidi_it.first_elt)
  5020                 n++;
  5021               while (n--)
  5022                 bidi_move_to_visually_next (&it_copy.bidi_it);
  5023 
  5024               SET_TEXT_POS (pos,
  5025                             it_copy.bidi_it.charpos, it_copy.bidi_it.bytepos);
  5026             }
  5027         }
  5028       eassert (BEGV <= CHARPOS (pos) && CHARPOS (pos) <= ZV);
  5029 
  5030       /* Determine face for CHARSET_ASCII, or unibyte.  */
  5031       face_id = face_at_buffer_position (it->w,
  5032                                          CHARPOS (pos),
  5033                                          &next_check_charpos,
  5034                                          limit, false, -1, 0);
  5035 
  5036       /* Correct the face for charsets different from ASCII.  Do it
  5037          for the multibyte case only.  The face returned above is
  5038          suitable for unibyte text if current_buffer is unibyte.  */
  5039       if (it->multibyte_p)
  5040         {
  5041           int c = FETCH_MULTIBYTE_CHAR (BYTEPOS (pos));
  5042           struct face *face = FACE_FROM_ID (it->f, face_id);
  5043           face_id = FACE_FOR_CHAR (it->f, face, c, CHARPOS (pos), Qnil);
  5044         }
  5045     }
  5046 
  5047   return face_id;
  5048 }
  5049 
  5050 
  5051 
  5052 /***********************************************************************
  5053                             Invisible text
  5054  ***********************************************************************/
  5055 
  5056 /* Set up iterator IT from invisible properties at its current
  5057    position.  Called from handle_stop.  */
  5058 
  5059 static enum prop_handled
  5060 handle_invisible_prop (struct it *it)
  5061 {
  5062   enum prop_handled handled = HANDLED_NORMALLY;
  5063   int invis;
  5064   Lisp_Object prop;
  5065 
  5066   if (STRINGP (it->string))
  5067     {
  5068       Lisp_Object end_charpos, limit;
  5069 
  5070       /* Get the value of the invisible text property at the
  5071          current position.  Value will be nil if there is no such
  5072          property.  */
  5073       end_charpos = make_fixnum (IT_STRING_CHARPOS (*it));
  5074       prop = Fget_text_property (end_charpos, Qinvisible, it->string);
  5075       invis = TEXT_PROP_MEANS_INVISIBLE (prop);
  5076 
  5077       if (invis != 0 && IT_STRING_CHARPOS (*it) < it->end_charpos)
  5078         {
  5079           /* Record whether we have to display an ellipsis for the
  5080              invisible text.  */
  5081           bool display_ellipsis_p = (invis == 2);
  5082           ptrdiff_t len, endpos;
  5083 
  5084           handled = HANDLED_RECOMPUTE_PROPS;
  5085 
  5086           /* Get the position at which the next visible text can be
  5087              found in IT->string, if any.  */
  5088           endpos = len = SCHARS (it->string);
  5089           XSETINT (limit, len);
  5090           do
  5091             {
  5092               end_charpos
  5093                 = Fnext_single_property_change (end_charpos, Qinvisible,
  5094                                                 it->string, limit);
  5095               /* Since LIMIT is always an integer, so should be the
  5096                  value returned by Fnext_single_property_change.  */
  5097               eassert (FIXNUMP (end_charpos));
  5098               if (FIXNUMP (end_charpos))
  5099                 {
  5100                   endpos = XFIXNAT (end_charpos);
  5101                   prop = Fget_text_property (end_charpos, Qinvisible, it->string);
  5102                   invis = TEXT_PROP_MEANS_INVISIBLE (prop);
  5103                   if (invis == 2)
  5104                     display_ellipsis_p = true;
  5105                 }
  5106               else /* Should never happen; but if it does, exit the loop.  */
  5107                 endpos = len;
  5108             }
  5109           while (invis != 0 && endpos < len);
  5110 
  5111           if (display_ellipsis_p)
  5112             it->ellipsis_p = true;
  5113 
  5114           if (endpos < len)
  5115             {
  5116               /* Text at END_CHARPOS is visible.  Move IT there.  */
  5117               struct text_pos old;
  5118               ptrdiff_t oldpos;
  5119 
  5120               old = it->current.string_pos;
  5121               oldpos = CHARPOS (old);
  5122               if (it->bidi_p)
  5123                 {
  5124                   if (it->bidi_it.first_elt
  5125                       && it->bidi_it.charpos < SCHARS (it->string))
  5126                     bidi_paragraph_init (it->paragraph_embedding,
  5127                                          &it->bidi_it, true);
  5128                   /* Bidi-iterate out of the invisible text.  */
  5129                   do
  5130                     {
  5131                       bidi_move_to_visually_next (&it->bidi_it);
  5132                     }
  5133                   while (oldpos <= it->bidi_it.charpos
  5134                          && it->bidi_it.charpos < endpos
  5135                          && it->bidi_it.charpos < it->bidi_it.string.schars);
  5136 
  5137                   IT_STRING_CHARPOS (*it) = it->bidi_it.charpos;
  5138                   IT_STRING_BYTEPOS (*it) = it->bidi_it.bytepos;
  5139                   if (IT_CHARPOS (*it) >= endpos)
  5140                     it->prev_stop = endpos;
  5141                 }
  5142               else
  5143                 {
  5144                   IT_STRING_CHARPOS (*it) = endpos;
  5145                   compute_string_pos (&it->current.string_pos, old, it->string);
  5146                 }
  5147             }
  5148           else
  5149             {
  5150               /* The rest of the string is invisible.  If this is an
  5151                  overlay string, proceed with the next overlay string
  5152                  or whatever comes and return a character from there.  */
  5153               if (it->current.overlay_string_index >= 0
  5154                   && !display_ellipsis_p)
  5155                 {
  5156                   next_overlay_string (it);
  5157                   /* Don't check for overlay strings when we just
  5158                      finished processing them.  */
  5159                   handled = HANDLED_OVERLAY_STRING_CONSUMED;
  5160                 }
  5161               else
  5162                 {
  5163                   IT_STRING_CHARPOS (*it) = SCHARS (it->string);
  5164                   IT_STRING_BYTEPOS (*it) = SBYTES (it->string);
  5165                 }
  5166             }
  5167         }
  5168     }
  5169   else
  5170     {
  5171       ptrdiff_t newpos, next_stop, start_charpos, tem;
  5172       Lisp_Object pos, overlay;
  5173 
  5174       /* First of all, is there invisible text at this position?  */
  5175       tem = start_charpos = IT_CHARPOS (*it);
  5176       pos = make_fixnum (tem);
  5177       prop = get_char_property_and_overlay (pos, Qinvisible, it->window,
  5178                                             &overlay);
  5179       invis = TEXT_PROP_MEANS_INVISIBLE (prop);
  5180 
  5181       /* If we are on invisible text, skip over it.  */
  5182       if (invis != 0 && start_charpos < it->end_charpos)
  5183         {
  5184           /* Record whether we have to display an ellipsis for the
  5185              invisible text.  */
  5186           bool display_ellipsis_p = invis == 2;
  5187 
  5188           handled = HANDLED_RECOMPUTE_PROPS;
  5189 
  5190           /* Loop skipping over invisible text.  The loop is left at
  5191              ZV or with IT on the first char being visible again.  */
  5192           do
  5193             {
  5194               /* Try to skip some invisible text.  Return value is the
  5195                  position reached which can be equal to where we start
  5196                  if there is nothing invisible there.  This skips both
  5197                  over invisible text properties and overlays with
  5198                  invisible property.  */
  5199               newpos = skip_invisible (tem, &next_stop, ZV, it->window);
  5200 
  5201               /* If we skipped nothing at all we weren't at invisible
  5202                  text in the first place.  If everything to the end of
  5203                  the buffer was skipped, end the loop.  */
  5204               if (newpos == tem || newpos >= ZV)
  5205                 invis = 0;
  5206               else
  5207                 {
  5208                   /* We skipped some characters but not necessarily
  5209                      all there are.  Check if we ended up on visible
  5210                      text.  Fget_char_property returns the property of
  5211                      the char before the given position, i.e. if we
  5212                      get invis = 0, this means that the char at
  5213                      newpos is visible.  */
  5214                   pos = make_fixnum (newpos);
  5215                   prop = Fget_char_property (pos, Qinvisible, it->window);
  5216                   invis = TEXT_PROP_MEANS_INVISIBLE (prop);
  5217                 }
  5218 
  5219               /* If we ended up on invisible text, proceed to
  5220                  skip starting with next_stop.  */
  5221               if (invis != 0)
  5222                 tem = next_stop;
  5223 
  5224               /* If there are adjacent invisible texts, don't lose the
  5225                  second one's ellipsis.  */
  5226               if (invis == 2)
  5227                 display_ellipsis_p = true;
  5228             }
  5229           while (invis != 0);
  5230 
  5231           /* The position newpos is now either ZV or on visible text.  */
  5232           if (it->bidi_p)
  5233             {
  5234               ptrdiff_t bpos = CHAR_TO_BYTE (newpos);
  5235               bool on_newline
  5236                 = bpos == ZV_BYTE || FETCH_BYTE (bpos) == '\n';
  5237               bool after_newline
  5238                 = newpos <= BEGV || FETCH_BYTE (bpos - 1) == '\n';
  5239 
  5240               /* If the invisible text ends on a newline or on a
  5241                  character after a newline, we can avoid the costly,
  5242                  character by character, bidi iteration to NEWPOS, and
  5243                  instead simply reseat the iterator there.  That's
  5244                  because all bidi reordering information is tossed at
  5245                  the newline.  This is a big win for modes that hide
  5246                  complete lines, like Outline, Org, etc.  */
  5247               if (on_newline || after_newline)
  5248                 {
  5249                   struct text_pos tpos;
  5250                   bidi_dir_t pdir = it->bidi_it.paragraph_dir;
  5251 
  5252                   SET_TEXT_POS (tpos, newpos, bpos);
  5253                   reseat_1 (it, tpos, false);
  5254                   /* If we reseat on a newline/ZV, we need to prep the
  5255                      bidi iterator for advancing to the next character
  5256                      after the newline/EOB, keeping the current paragraph
  5257                      direction (so that PRODUCE_GLYPHS does TRT wrt
  5258                      prepending/appending glyphs to a glyph row).  */
  5259                   if (on_newline)
  5260                     {
  5261                       it->bidi_it.first_elt = false;
  5262                       it->bidi_it.paragraph_dir = pdir;
  5263                       it->bidi_it.ch = (bpos == ZV_BYTE) ? -1 : '\n';
  5264                       it->bidi_it.nchars = 1;
  5265                       it->bidi_it.ch_len = 1;
  5266                     }
  5267                 }
  5268               else      /* Must use the slow method.  */
  5269                 {
  5270                   /* With bidi iteration, the region of invisible text
  5271                      could start and/or end in the middle of a
  5272                      non-base embedding level.  Therefore, we need to
  5273                      skip invisible text using the bidi iterator,
  5274                      starting at IT's current position, until we find
  5275                      ourselves outside of the invisible text.
  5276                      Skipping invisible text _after_ bidi iteration
  5277                      avoids affecting the visual order of the
  5278                      displayed text when invisible properties are
  5279                      added or removed.  */
  5280                   if (it->bidi_it.first_elt && it->bidi_it.charpos < ZV)
  5281                     {
  5282                       /* If we were `reseat'ed to a new paragraph,
  5283                          determine the paragraph base direction.  We
  5284                          need to do it now because
  5285                          next_element_from_buffer may not have a
  5286                          chance to do it, if we are going to skip any
  5287                          text at the beginning, which resets the
  5288                          FIRST_ELT flag.  */
  5289                       bidi_paragraph_init (it->paragraph_embedding,
  5290                                            &it->bidi_it, true);
  5291                     }
  5292                   do
  5293                     {
  5294                       bidi_move_to_visually_next (&it->bidi_it);
  5295                     }
  5296                   while (it->stop_charpos <= it->bidi_it.charpos
  5297                          && it->bidi_it.charpos < newpos);
  5298                   IT_CHARPOS (*it) = it->bidi_it.charpos;
  5299                   IT_BYTEPOS (*it) = it->bidi_it.bytepos;
  5300                   /* If we overstepped NEWPOS, record its position in
  5301                      the iterator, so that we skip invisible text if
  5302                      later the bidi iteration lands us in the
  5303                      invisible region again. */
  5304                   if (IT_CHARPOS (*it) >= newpos)
  5305                     it->prev_stop = newpos;
  5306                 }
  5307             }
  5308           else
  5309             {
  5310               IT_CHARPOS (*it) = newpos;
  5311               IT_BYTEPOS (*it) = CHAR_TO_BYTE (newpos);
  5312             }
  5313 
  5314           if (display_ellipsis_p)
  5315             {
  5316               /* Make sure that the glyphs of the ellipsis will get
  5317                  correct `charpos' values.  If we would not update
  5318                  it->position here, the glyphs would belong to the
  5319                  last visible character _before_ the invisible
  5320                  text, which confuses `set_cursor_from_row'.
  5321 
  5322                  We use the last invisible position instead of the
  5323                  first because this way the cursor is always drawn on
  5324                  the first "." of the ellipsis, whenever PT is inside
  5325                  the invisible text.  Otherwise the cursor would be
  5326                  placed _after_ the ellipsis when the point is after the
  5327                  first invisible character.  */
  5328               if (!STRINGP (it->object))
  5329                 {
  5330                   it->position.charpos = newpos - 1;
  5331                   it->position.bytepos = CHAR_TO_BYTE (it->position.charpos);
  5332                 }
  5333             }
  5334 
  5335           /* If there are before-strings at the start of invisible
  5336              text, and the text is invisible because of a text
  5337              property, arrange to show before-strings because 20.x did
  5338              it that way.  (If the text is invisible because of an
  5339              overlay property instead of a text property, this is
  5340              already handled in the overlay code.)  */
  5341           if (NILP (overlay)
  5342               && get_overlay_strings (it, it->stop_charpos))
  5343             {
  5344               handled = HANDLED_RECOMPUTE_PROPS;
  5345               if (it->sp > 0)
  5346                 {
  5347                   it->stack[it->sp - 1].display_ellipsis_p = display_ellipsis_p;
  5348                   /* The call to get_overlay_strings above recomputes
  5349                      it->stop_charpos, but it only considers changes
  5350                      in properties and overlays beyond iterator's
  5351                      current position.  This causes us to miss changes
  5352                      that happen exactly where the invisible property
  5353                      ended.  So we play it safe here and force the
  5354                      iterator to check for potential stop positions
  5355                      immediately after the invisible text.  Note that
  5356                      if get_overlay_strings returns true, it
  5357                      normally also pushed the iterator stack, so we
  5358                      need to update the stop position in the slot
  5359                      below the current one.  */
  5360                   it->stack[it->sp - 1].stop_charpos
  5361                     = CHARPOS (it->stack[it->sp - 1].current.pos);
  5362                 }
  5363             }
  5364           else if (display_ellipsis_p)
  5365             {
  5366               it->ellipsis_p = true;
  5367               /* Let the ellipsis display before
  5368                  considering any properties of the following char.
  5369                  Fixes jasonr@gnu.org 01 Oct 07 bug.  */
  5370               handled = HANDLED_RETURN;
  5371             }
  5372         }
  5373     }
  5374 
  5375   return handled;
  5376 }
  5377 
  5378 
  5379 /* Make iterator IT return `...' next.
  5380    Replaces LEN characters from buffer.  */
  5381 
  5382 static void
  5383 setup_for_ellipsis (struct it *it, int len)
  5384 {
  5385   /* Use the display table definition for `...'.  Invalid glyphs
  5386      will be handled by the method returning elements from dpvec.  */
  5387   if (it->dp && VECTORP (DISP_INVIS_VECTOR (it->dp)))
  5388     {
  5389       struct Lisp_Vector *v = XVECTOR (DISP_INVIS_VECTOR (it->dp));
  5390       it->dpvec = v->contents;
  5391       it->dpend = v->contents + v->header.size;
  5392     }
  5393   else
  5394     {
  5395       /* Default `...'.  */
  5396       it->dpvec = default_invis_vector;
  5397       it->dpend = default_invis_vector + 3;
  5398     }
  5399 
  5400   it->dpvec_char_len = len;
  5401   it->current.dpvec_index = 0;
  5402   it->dpvec_face_id = -1;
  5403 
  5404   /* Use IT->saved_face_id for the ellipsis, so that it has the same
  5405      face as the preceding text.  IT->saved_face_id was set in
  5406      handle_stop to the face of the preceding character, and will be
  5407      different from IT->face_id only if the invisible text skipped in
  5408      handle_invisible_prop has some non-default face on its first
  5409      character.  We thus ignore the face of the invisible text when we
  5410      display the ellipsis.  IT's face is restored in set_iterator_to_next.  */
  5411   if (it->saved_face_id >= 0)
  5412     it->face_id = it->saved_face_id;
  5413 
  5414   /* If the ellipsis represents buffer text, it means we advanced in
  5415      the buffer, so we should no longer ignore overlay strings.  */
  5416   if (it->method == GET_FROM_BUFFER)
  5417     it->ignore_overlay_strings_at_pos_p = false;
  5418 
  5419   it->method = GET_FROM_DISPLAY_VECTOR;
  5420   it->ellipsis_p = true;
  5421 }
  5422 
  5423 
  5424 static Lisp_Object
  5425 find_display_property (Lisp_Object disp, Lisp_Object prop)
  5426 {
  5427   if (NILP (disp))
  5428     return Qnil;
  5429   /* We have a vector of display specs.  */
  5430   if (VECTORP (disp))
  5431     {
  5432       for (ptrdiff_t i = 0; i < ASIZE (disp); i++)
  5433         {
  5434           Lisp_Object elem = AREF (disp, i);
  5435           if (CONSP (elem)
  5436               && CONSP (XCDR (elem))
  5437               && EQ (XCAR (elem), prop))
  5438             return XCAR (XCDR (elem));
  5439         }
  5440       return Qnil;
  5441     }
  5442   /* We have a list of display specs.  */
  5443   else if (CONSP (disp)
  5444            && CONSP (XCAR (disp)))
  5445     {
  5446       while (!NILP (disp))
  5447         {
  5448           Lisp_Object elem = XCAR (disp);
  5449           if (CONSP (elem)
  5450               && CONSP (XCDR (elem))
  5451               && EQ (XCAR (elem), prop))
  5452             return XCAR (XCDR (elem));
  5453 
  5454           /* Check that we have a proper list before going to the next
  5455              element.  */
  5456           if (CONSP (XCDR (disp)))
  5457             disp = XCDR (disp);
  5458           else
  5459             disp = Qnil;
  5460         }
  5461       return Qnil;
  5462     }
  5463   /* A simple display spec.  */
  5464   else if (CONSP (disp)
  5465            && CONSP (XCDR (disp))
  5466            && EQ (XCAR (disp), prop))
  5467     return XCAR (XCDR (disp));
  5468   else
  5469     return Qnil;
  5470 }
  5471 
  5472 static Lisp_Object
  5473 get_display_property (ptrdiff_t bufpos, Lisp_Object prop, Lisp_Object object)
  5474 {
  5475   return find_display_property (Fget_text_property (make_fixnum (bufpos),
  5476                                                     Qdisplay, object),
  5477                                 prop);
  5478 }
  5479 
  5480 static void
  5481 display_min_width (struct it *it, ptrdiff_t bufpos,
  5482                    Lisp_Object object, Lisp_Object width_spec)
  5483 {
  5484   /* We're being called at the end of the `min-width' sequence,
  5485      probably. */
  5486   if (!NILP (it->min_width_property)
  5487       && !EQ (width_spec, it->min_width_property))
  5488     {
  5489       if (!it->glyph_row)
  5490         return;
  5491 
  5492       /* When called from display_string (i.e., the mode line),
  5493          we're being called with a string as the object, and we
  5494          may be called with many sub-strings belonging to the same
  5495          :propertize run. */
  5496       if ((bufpos == 0
  5497            && !EQ (it->min_width_property,
  5498                    get_display_property (0, Qmin_width, object)))
  5499           /* In a buffer -- check that we're really right after the
  5500              sequence of characters covered by this `min-width'.  */
  5501           || (bufpos > BEGV
  5502               && EQ (it->min_width_property,
  5503                      get_display_property (bufpos - 1, Qmin_width, object))))
  5504         {
  5505           Lisp_Object w = Qnil;
  5506           double width;
  5507 #ifdef HAVE_WINDOW_SYSTEM
  5508           if (FRAME_WINDOW_P (it->f))
  5509             {
  5510               struct font *font = NULL;
  5511               struct face *face = FACE_FROM_ID (it->f, it->face_id);
  5512               font = face->font ? face->font : FRAME_FONT (it->f);
  5513               calc_pixel_width_or_height (&width, it,
  5514                                           XCAR (it->min_width_property),
  5515                                           font, true, NULL);
  5516               width -= it->current_x - it->min_width_start;
  5517               w = list1 (make_int (width));
  5518             }
  5519           else
  5520 #endif
  5521             {
  5522               calc_pixel_width_or_height (&width, it,
  5523                                           XCAR (it->min_width_property),
  5524                                           NULL, true, NULL);
  5525               width -= (it->current_x - it->min_width_start) /
  5526                 FRAME_COLUMN_WIDTH (it->f);
  5527               w = make_int (width);
  5528             }
  5529 
  5530           /* Insert the stretch glyph.  */
  5531           it->object = list3 (Qspace, QCwidth, w);
  5532           produce_stretch_glyph (it);
  5533           if (it->area == TEXT_AREA)
  5534             it->current_x += it->pixel_width;
  5535           it->min_width_property = Qnil;
  5536         }
  5537     }
  5538 
  5539   /* We're at the start of a `min-width' sequence -- record the
  5540      position and the property, so that we can later see if we're at
  5541      the end.  */
  5542   if (CONSP (width_spec))
  5543     {
  5544       if (bufpos == BEGV
  5545           /* Mode line (see above).  */
  5546           || (bufpos == 0
  5547               && !EQ (it->min_width_property,
  5548                       get_display_property (0, Qmin_width, object)))
  5549           /* Buffer.  */
  5550           || (bufpos > BEGV
  5551               && !EQ (width_spec,
  5552                       get_display_property (bufpos - 1, Qmin_width, object))))
  5553         {
  5554           it->min_width_property = width_spec;
  5555           it->min_width_start = it->current_x;
  5556         }
  5557     }
  5558 }
  5559 
  5560 DEFUN ("get-display-property", Fget_display_property,
  5561        Sget_display_property, 2, 4, 0,
  5562        doc: /* Get the value of the `display' property PROP at POSITION.
  5563 If OBJECT, this should be a buffer or string where the property is
  5564 fetched from.  If omitted, OBJECT defaults to the current buffer.
  5565 
  5566 If PROPERTIES, look for value of PROP in PROPERTIES instead of the
  5567 properties at POSITION.  */)
  5568   (Lisp_Object position, Lisp_Object prop, Lisp_Object object,
  5569    Lisp_Object properties)
  5570 {
  5571   if (NILP (properties))
  5572     properties = Fget_text_property (position, Qdisplay, object);
  5573   else
  5574     CHECK_LIST (properties);
  5575 
  5576   return find_display_property (properties, prop);
  5577 }
  5578 
  5579 
  5580 
  5581 /***********************************************************************
  5582                             'display' property
  5583  ***********************************************************************/
  5584 
  5585 /* Set up iterator IT from `display' property at its current position.
  5586    Called from handle_stop.
  5587    We return HANDLED_RETURN if some part of the display property
  5588    overrides the display of the buffer text itself.
  5589    Otherwise we return HANDLED_NORMALLY.  */
  5590 
  5591 static enum prop_handled
  5592 handle_display_prop (struct it *it)
  5593 {
  5594   Lisp_Object propval, object, overlay;
  5595   struct text_pos *position;
  5596   ptrdiff_t bufpos;
  5597   /* Nonzero if some property replaces the display of the text itself.  */
  5598   int display_replaced = 0;
  5599 
  5600   if (STRINGP (it->string))
  5601     {
  5602       object = it->string;
  5603       position = &it->current.string_pos;
  5604       bufpos = CHARPOS (it->current.pos);
  5605     }
  5606   else
  5607     {
  5608       XSETWINDOW (object, it->w);
  5609       position = &it->current.pos;
  5610       bufpos = CHARPOS (*position);
  5611     }
  5612 
  5613   /* Reset those iterator values set from display property values.  */
  5614   it->slice.x = it->slice.y = it->slice.width = it->slice.height = Qnil;
  5615   it->space_width = Qnil;
  5616   it->font_height = Qnil;
  5617   it->voffset = 0;
  5618 
  5619   /* We don't support recursive `display' properties, i.e. string
  5620      values that have a string `display' property, that have a string
  5621      `display' property etc.  */
  5622   if (!it->string_from_display_prop_p)
  5623     it->area = TEXT_AREA;
  5624 
  5625   propval = get_char_property_and_overlay (make_fixnum (position->charpos),
  5626                                            Qdisplay, object, &overlay);
  5627 
  5628   /* Rest of the code must have OBJECT be either a string or a buffer.  */
  5629   if (!STRINGP (it->string))
  5630     object = it->w->contents;
  5631 
  5632   /* Handle min-width ends. */
  5633   if (!NILP (it->min_width_property)
  5634       && NILP (find_display_property (propval, Qmin_width)))
  5635     display_min_width (it, bufpos, object, Qnil);
  5636 
  5637   if (NILP (propval))
  5638     return HANDLED_NORMALLY;
  5639   /* Now OVERLAY is the overlay that gave us this property, or nil
  5640      if it was a text property.  */
  5641 
  5642   display_replaced = handle_display_spec (it, propval, object, overlay,
  5643                                           position, bufpos,
  5644                                           FRAME_WINDOW_P (it->f));
  5645   return display_replaced != 0 ? HANDLED_RETURN : HANDLED_NORMALLY;
  5646 }
  5647 
  5648 /* Subroutine of handle_display_prop.  Returns non-zero if the display
  5649    specification in SPEC is a replacing specification, i.e. it would
  5650    replace the text covered by `display' property with something else,
  5651    such as an image or a display string.  If SPEC includes any kind or
  5652    `(space ...) specification, the value is 2; this is used by
  5653    compute_display_string_pos, which see.
  5654 
  5655    See handle_single_display_spec for documentation of arguments.
  5656    FRAME_WINDOW_P is true if the window being redisplayed is on a
  5657    GUI frame; this argument is used only if IT is NULL, see below.
  5658 
  5659    IT can be NULL, if this is called by the bidi reordering code
  5660    through compute_display_string_pos, which see.  In that case, this
  5661    function only examines SPEC, but does not otherwise "handle" it, in
  5662    the sense that it doesn't set up members of IT from the display
  5663    spec.  */
  5664 static int
  5665 handle_display_spec (struct it *it, Lisp_Object spec, Lisp_Object object,
  5666                      Lisp_Object overlay, struct text_pos *position,
  5667                      ptrdiff_t bufpos, bool frame_window_p)
  5668 {
  5669   int replacing = 0;
  5670   bool enable_eval = true;
  5671 
  5672   /* Support (disable-eval PROP) which is used by enriched.el.  */
  5673   if (CONSP (spec) && EQ (XCAR (spec), Qdisable_eval))
  5674     {
  5675       enable_eval = false;
  5676       spec = CONSP (XCDR (spec)) ? XCAR (XCDR (spec)) : Qnil;
  5677     }
  5678 
  5679   if (CONSP (spec)
  5680       /* Simple specifications.  */
  5681       && !EQ (XCAR (spec), Qimage)
  5682 #ifdef HAVE_XWIDGETS
  5683       && !EQ (XCAR (spec), Qxwidget)
  5684 #endif
  5685       && !EQ (XCAR (spec), Qspace)
  5686       && !EQ (XCAR (spec), Qwhen)
  5687       && !EQ (XCAR (spec), Qslice)
  5688       && !EQ (XCAR (spec), Qspace_width)
  5689       && !EQ (XCAR (spec), Qheight)
  5690       && !EQ (XCAR (spec), Qraise)
  5691       /* Marginal area specifications.  */
  5692       && !(CONSP (XCAR (spec)) && EQ (XCAR (XCAR (spec)), Qmargin))
  5693       && !EQ (XCAR (spec), Qleft_fringe)
  5694       && !EQ (XCAR (spec), Qright_fringe)
  5695       && !EQ (XCAR (spec), Qmin_width)
  5696       && !NILP (XCAR (spec)))
  5697     {
  5698       for (; CONSP (spec); spec = XCDR (spec))
  5699         {
  5700           int rv = handle_single_display_spec (it, XCAR (spec), object,
  5701                                                overlay, position, bufpos,
  5702                                                replacing, frame_window_p,
  5703                                                enable_eval);
  5704           if (rv != 0)
  5705             {
  5706               replacing = rv;
  5707               /* If some text in a string is replaced, `position' no
  5708                  longer points to the position of `object'.  */
  5709               if (!it || STRINGP (object))
  5710                 break;
  5711             }
  5712         }
  5713     }
  5714   else if (VECTORP (spec))
  5715     {
  5716       ptrdiff_t i;
  5717       for (i = 0; i < ASIZE (spec); ++i)
  5718         {
  5719           int rv = handle_single_display_spec (it, AREF (spec, i), object,
  5720                                                overlay, position, bufpos,
  5721                                                replacing, frame_window_p,
  5722                                                enable_eval);
  5723           if (rv != 0)
  5724             {
  5725               replacing = rv;
  5726               /* If some text in a string is replaced, `position' no
  5727                  longer points to the position of `object'.  */
  5728               if (!it || STRINGP (object))
  5729                 break;
  5730             }
  5731         }
  5732     }
  5733   else
  5734     replacing = handle_single_display_spec (it, spec, object, overlay, position,
  5735                                             bufpos, 0, frame_window_p,
  5736                                             enable_eval);
  5737   return replacing;
  5738 }
  5739 
  5740 /* Value is the position of the end of the `display' property starting
  5741    at START_POS in OBJECT.  */
  5742 
  5743 static struct text_pos
  5744 display_prop_end (struct it *it, Lisp_Object object, struct text_pos start_pos)
  5745 {
  5746   Lisp_Object end;
  5747   struct text_pos end_pos;
  5748 
  5749   end = Fnext_single_char_property_change (make_fixnum (CHARPOS (start_pos)),
  5750                                            Qdisplay, object, Qnil);
  5751   CHARPOS (end_pos) = XFIXNAT (end);
  5752   if (STRINGP (object))
  5753     compute_string_pos (&end_pos, start_pos, it->string);
  5754   else
  5755     BYTEPOS (end_pos) = CHAR_TO_BYTE (XFIXNAT (end));
  5756 
  5757   return end_pos;
  5758 }
  5759 
  5760 
  5761 /* Set up IT from a single `display' property specification SPEC.  OBJECT
  5762    is the object in which the `display' property was found.  *POSITION
  5763    is the position in OBJECT at which the `display' property was found.
  5764    BUFPOS is the buffer position of OBJECT (different from POSITION if
  5765    OBJECT is not a buffer).  DISPLAY_REPLACED non-zero means that we
  5766    previously saw a display specification which already replaced text
  5767    display with something else, for example an image; we ignore such
  5768    properties after the first one has been processed.
  5769 
  5770    OVERLAY is the overlay this `display' property came from,
  5771    or nil if it was a text property.
  5772 
  5773    If SPEC is a `space' or `image' specification, and in some other
  5774    cases too, set *POSITION to the position where the `display'
  5775    property ends.
  5776 
  5777    If IT is NULL, only examine the property specification in SPEC, but
  5778    don't set up IT.  In that case, FRAME_WINDOW_P means SPEC
  5779    is intended to be displayed in a window on a GUI frame.
  5780 
  5781    Enable evaluation of Lisp forms only if ENABLE_EVAL_P is true.
  5782 
  5783    Value is non-zero if something was found which replaces the display
  5784    of buffer or string text.  */
  5785 
  5786 static int
  5787 handle_single_display_spec (struct it *it, Lisp_Object spec, Lisp_Object object,
  5788                             Lisp_Object overlay, struct text_pos *position,
  5789                             ptrdiff_t bufpos, int display_replaced,
  5790                             bool frame_window_p, bool enable_eval_p)
  5791 {
  5792   Lisp_Object form;
  5793   Lisp_Object location, value;
  5794   struct text_pos start_pos = *position;
  5795   void *itdata = NULL;
  5796 
  5797   /* If SPEC is a list of the form `(when FORM . VALUE)', evaluate FORM.
  5798      If the result is non-nil, use VALUE instead of SPEC.  */
  5799   form = Qt;
  5800   if (CONSP (spec) && EQ (XCAR (spec), Qwhen))
  5801     {
  5802       spec = XCDR (spec);
  5803       if (!CONSP (spec))
  5804         return 0;
  5805       form = XCAR (spec);
  5806       spec = XCDR (spec);
  5807     }
  5808 
  5809   if (!NILP (form) && !EQ (form, Qt) && !enable_eval_p)
  5810     form = Qnil;
  5811   if (!NILP (form) && !EQ (form, Qt))
  5812     {
  5813       specpdl_ref count = SPECPDL_INDEX ();
  5814 
  5815       /* Bind `object' to the object having the `display' property, a
  5816          buffer or string.  Bind `position' to the position in the
  5817          object where the property was found, and `buffer-position'
  5818          to the current position in the buffer.  */
  5819 
  5820       if (NILP (object))
  5821         XSETBUFFER (object, current_buffer);
  5822       specbind (Qobject, object);
  5823       specbind (Qposition, make_fixnum (CHARPOS (*position)));
  5824       specbind (Qbuffer_position, make_fixnum (bufpos));
  5825       /* Save and restore the bidi cache, since FORM could be crazy
  5826          enough to re-enter redisplay, e.g., by calling 'message'.  */
  5827       itdata = bidi_shelve_cache ();
  5828       form = safe_eval (form);
  5829       bidi_unshelve_cache (itdata, false);
  5830       form = unbind_to (count, form);
  5831     }
  5832 
  5833   if (NILP (form))
  5834     return 0;
  5835 
  5836   /* Handle `(height HEIGHT)' specifications.  */
  5837   if (CONSP (spec)
  5838       && EQ (XCAR (spec), Qheight)
  5839       && CONSP (XCDR (spec)))
  5840     {
  5841       if (it)
  5842         {
  5843           if (!FRAME_WINDOW_P (it->f))
  5844             return 0;
  5845 
  5846           it->font_height = XCAR (XCDR (spec));
  5847           if (!NILP (it->font_height))
  5848             {
  5849               int new_height = -1;
  5850 
  5851               if (CONSP (it->font_height)
  5852                   && (EQ (XCAR (it->font_height), Qplus)
  5853                       || EQ (XCAR (it->font_height), Qminus))
  5854                   && CONSP (XCDR (it->font_height))
  5855                   && RANGED_FIXNUMP (0, XCAR (XCDR (it->font_height)), INT_MAX))
  5856                 {
  5857                   /* `(+ N)' or `(- N)' where N is an integer.  */
  5858                   int steps = XFIXNUM (XCAR (XCDR (it->font_height)));
  5859                   if (EQ (XCAR (it->font_height), Qplus))
  5860                     steps = - steps;
  5861                   it->face_id = smaller_face (it->f, it->face_id, steps);
  5862                 }
  5863               else if (FUNCTIONP (it->font_height) && enable_eval_p)
  5864                 {
  5865                   /* Call function with current height as argument.
  5866                      Value is the new height.  */
  5867                   struct face *face = FACE_FROM_ID (it->f, it->face_id);
  5868                   Lisp_Object height;
  5869                   itdata = bidi_shelve_cache ();
  5870                   height = safe_call1 (it->font_height,
  5871                                        face->lface[LFACE_HEIGHT_INDEX]);
  5872                   bidi_unshelve_cache (itdata, false);
  5873                   if (NUMBERP (height))
  5874                     new_height = XFLOATINT (height);
  5875                 }
  5876               else if (NUMBERP (it->font_height))
  5877                 {
  5878                   /* Value is a multiple of the canonical char height.  */
  5879                   struct face *f;
  5880 
  5881                   f = FACE_FROM_ID (it->f,
  5882                                     lookup_basic_face (it->w, it->f, DEFAULT_FACE_ID));
  5883                   new_height = (XFLOATINT (it->font_height)
  5884                                 * XFIXNUM (f->lface[LFACE_HEIGHT_INDEX]));
  5885                 }
  5886               else if (enable_eval_p)
  5887                 {
  5888                   /* Evaluate IT->font_height with `height' bound to the
  5889                      current specified height to get the new height.  */
  5890                   specpdl_ref count = SPECPDL_INDEX ();
  5891                   struct face *face = FACE_FROM_ID (it->f, it->face_id);
  5892 
  5893                   specbind (Qheight, face->lface[LFACE_HEIGHT_INDEX]);
  5894                   itdata = bidi_shelve_cache ();
  5895                   value = safe_eval (it->font_height);
  5896                   bidi_unshelve_cache (itdata, false);
  5897                   value = unbind_to (count, value);
  5898 
  5899                   if (NUMBERP (value))
  5900                     new_height = XFLOATINT (value);
  5901                 }
  5902 
  5903               if (new_height > 0)
  5904                 it->face_id = face_with_height (it->f, it->face_id, new_height);
  5905             }
  5906         }
  5907 
  5908       return 0;
  5909     }
  5910 
  5911   /* Handle `(space-width WIDTH)'.  */
  5912   if (CONSP (spec)
  5913       && EQ (XCAR (spec), Qspace_width)
  5914       && CONSP (XCDR (spec)))
  5915     {
  5916       if (it)
  5917         {
  5918           if (!FRAME_WINDOW_P (it->f))
  5919             return 0;
  5920 
  5921           value = XCAR (XCDR (spec));
  5922           if (NUMBERP (value) && XFLOATINT (value) > 0)
  5923             it->space_width = value;
  5924         }
  5925 
  5926       return 0;
  5927     }
  5928 
  5929   /* Handle `(min-width (WIDTH))'.  */
  5930   if (CONSP (spec)
  5931       && EQ (XCAR (spec), Qmin_width)
  5932       && CONSP (XCDR (spec))
  5933       && CONSP (XCAR (XCDR (spec))))
  5934     {
  5935       if (it)
  5936         display_min_width (it, bufpos, object, XCAR (XCDR (spec)));
  5937       return 0;
  5938     }
  5939 
  5940   /* Handle `(slice X Y WIDTH HEIGHT)'.  */
  5941   if (CONSP (spec)
  5942       && EQ (XCAR (spec), Qslice))
  5943     {
  5944       Lisp_Object tem;
  5945 
  5946       if (it)
  5947         {
  5948           if (!FRAME_WINDOW_P (it->f))
  5949             return 0;
  5950 
  5951           if (tem = XCDR (spec), CONSP (tem))
  5952             {
  5953               it->slice.x = XCAR (tem);
  5954               if (tem = XCDR (tem), CONSP (tem))
  5955                 {
  5956                   it->slice.y = XCAR (tem);
  5957                   if (tem = XCDR (tem), CONSP (tem))
  5958                     {
  5959                       it->slice.width = XCAR (tem);
  5960                       if (tem = XCDR (tem), CONSP (tem))
  5961                         it->slice.height = XCAR (tem);
  5962                     }
  5963                 }
  5964             }
  5965         }
  5966 
  5967       return 0;
  5968     }
  5969 
  5970   /* Handle `(raise FACTOR)'.  */
  5971   if (CONSP (spec)
  5972       && EQ (XCAR (spec), Qraise)
  5973       && CONSP (XCDR (spec)))
  5974     {
  5975       if (it)
  5976         {
  5977           if (!FRAME_WINDOW_P (it->f))
  5978             return 0;
  5979 
  5980 #ifdef HAVE_WINDOW_SYSTEM
  5981           value = XCAR (XCDR (spec));
  5982           if (NUMBERP (value))
  5983             {
  5984               struct face *face = FACE_FROM_ID (it->f, it->face_id);
  5985               it->voffset = - (XFLOATINT (value)
  5986                                * (normal_char_height (face->font, -1)));
  5987             }
  5988 #endif /* HAVE_WINDOW_SYSTEM */
  5989         }
  5990 
  5991       return 0;
  5992     }
  5993 
  5994   /* Don't handle the other kinds of display specifications
  5995      inside a string that we got from a `display' property.  */
  5996   if (it && it->string_from_display_prop_p)
  5997     return 0;
  5998 
  5999   /* Characters having this form of property are not displayed, so
  6000      we have to find the end of the property.  */
  6001   if (it)
  6002     {
  6003       start_pos = *position;
  6004       *position = display_prop_end (it, object, start_pos);
  6005       /* If the display property comes from an overlay, don't consider
  6006          any potential stop_charpos values before the end of that
  6007          overlay.  Since display_prop_end will happily find another
  6008          'display' property coming from some other overlay or text
  6009          property on buffer positions before this overlay's end, we
  6010          need to ignore them, or else we risk displaying this
  6011          overlay's display string/image twice.  */
  6012       if (!NILP (overlay))
  6013         {
  6014           ptrdiff_t ovendpos = OVERLAY_END (overlay);
  6015 
  6016           /* Some borderline-sane Lisp might call us with the current
  6017              buffer narrowed so that overlay-end is outside the
  6018              POINT_MIN..POINT_MAX region, which will then cause
  6019              various assertion violations and crashes down the road,
  6020              starting with pop_it when it will attempt to use POSITION
  6021              set below.  Prevent that.  */
  6022           ovendpos = clip_to_bounds (BEGV, ovendpos, ZV);
  6023 
  6024           if (ovendpos > CHARPOS (*position))
  6025             SET_TEXT_POS (*position, ovendpos, CHAR_TO_BYTE (ovendpos));
  6026         }
  6027     }
  6028   value = Qnil;
  6029 
  6030   /* Stop the scan at that end position--we assume that all
  6031      text properties change there.  */
  6032   if (it)
  6033     it->stop_charpos = position->charpos;
  6034 
  6035   /* Handle `(left-fringe BITMAP [FACE])'
  6036      and `(right-fringe BITMAP [FACE])'.  */
  6037   if (CONSP (spec)
  6038       && (EQ (XCAR (spec), Qleft_fringe)
  6039           || EQ (XCAR (spec), Qright_fringe))
  6040       && CONSP (XCDR (spec)))
  6041     {
  6042       if (it)
  6043         {
  6044           if (!FRAME_WINDOW_P (it->f))
  6045             /* If we return here, POSITION has been advanced
  6046                across the text with this property.  */
  6047             {
  6048               /* Synchronize the bidi iterator with POSITION.  This is
  6049                  needed because we are not going to push the iterator
  6050                  on behalf of this display property, so there will be
  6051                  no pop_it call to do this synchronization for us.  */
  6052               if (it->bidi_p)
  6053                 {
  6054                   it->position = *position;
  6055                   iterate_out_of_display_property (it);
  6056                   *position = it->position;
  6057                 }
  6058               return 1;
  6059             }
  6060         }
  6061       else if (!frame_window_p)
  6062         return 1;
  6063 
  6064 #ifdef HAVE_WINDOW_SYSTEM
  6065       value = XCAR (XCDR (spec));
  6066       int fringe_bitmap = SYMBOLP (value) ? lookup_fringe_bitmap (value) : 0;
  6067       if (! fringe_bitmap)
  6068         /* If we return here, POSITION has been advanced
  6069            across the text with this property.  */
  6070         {
  6071           if (it && it->bidi_p)
  6072             {
  6073               it->position = *position;
  6074               iterate_out_of_display_property (it);
  6075               *position = it->position;
  6076             }
  6077           return 1;
  6078         }
  6079 
  6080       if (it)
  6081         {
  6082           int face_id = lookup_basic_face (it->w, it->f, DEFAULT_FACE_ID);
  6083 
  6084           if (CONSP (XCDR (XCDR (spec))))
  6085             {
  6086               Lisp_Object face_name = XCAR (XCDR (XCDR (spec)));
  6087               int face_id2;
  6088               /* Don't allow quitting from lookup_derived_face, for when
  6089                  we are displaying a non-selected window, and the buffer's
  6090                  point was temporarily moved to the window-point.  */
  6091               specpdl_ref count1 = SPECPDL_INDEX ();
  6092               specbind (Qinhibit_quit, Qt);
  6093               face_id2 = lookup_derived_face (it->w, it->f, face_name,
  6094                                               FRINGE_FACE_ID, false);
  6095               unbind_to (count1, Qnil);
  6096               if (face_id2 >= 0)
  6097                 face_id = face_id2;
  6098             }
  6099 
  6100           /* Save current settings of IT so that we can restore them
  6101              when we are finished with the glyph property value.  */
  6102           push_it (it, position);
  6103 
  6104           it->area = TEXT_AREA;
  6105           it->what = IT_IMAGE;
  6106           it->image_id = -1; /* no image */
  6107           it->position = start_pos;
  6108           it->object = NILP (object) ? it->w->contents : object;
  6109           it->method = GET_FROM_IMAGE;
  6110           it->from_overlay = Qnil;
  6111           it->face_id = face_id;
  6112           it->from_disp_prop_p = true;
  6113 
  6114           /* Say that we haven't consumed the characters with
  6115              `display' property yet.  The call to pop_it in
  6116              set_iterator_to_next will clean this up.  */
  6117           *position = start_pos;
  6118 
  6119           if (EQ (XCAR (spec), Qleft_fringe))
  6120             {
  6121               it->left_user_fringe_bitmap = fringe_bitmap;
  6122               it->left_user_fringe_face_id = face_id;
  6123             }
  6124           else
  6125             {
  6126               it->right_user_fringe_bitmap = fringe_bitmap;
  6127               it->right_user_fringe_face_id = face_id;
  6128             }
  6129         }
  6130 #endif /* HAVE_WINDOW_SYSTEM */
  6131       return 1;
  6132     }
  6133 
  6134   /* Prepare to handle `((margin left-margin) ...)',
  6135      `((margin right-margin) ...)' and `((margin nil) ...)'
  6136      prefixes for display specifications.  */
  6137   location = Qunbound;
  6138   if (CONSP (spec) && CONSP (XCAR (spec)))
  6139     {
  6140       Lisp_Object tem;
  6141 
  6142       value = XCDR (spec);
  6143       if (CONSP (value))
  6144         value = XCAR (value);
  6145 
  6146       tem = XCAR (spec);
  6147       if (EQ (XCAR (tem), Qmargin)
  6148           && (tem = XCDR (tem),
  6149               tem = CONSP (tem) ? XCAR (tem) : Qnil,
  6150               (NILP (tem)
  6151                || EQ (tem, Qleft_margin)
  6152                || EQ (tem, Qright_margin))))
  6153         location = tem;
  6154     }
  6155 
  6156   if (BASE_EQ (location, Qunbound))
  6157     {
  6158       location = Qnil;
  6159       value = spec;
  6160     }
  6161 
  6162   /* After this point, VALUE is the property after any
  6163      margin prefix has been stripped.  It must be a string,
  6164      an image specification, or `(space ...)'.
  6165 
  6166      LOCATION specifies where to display: `left-margin',
  6167      `right-margin' or nil.  */
  6168 
  6169   bool valid_p = (STRINGP (value)
  6170 #ifdef HAVE_WINDOW_SYSTEM
  6171                   || ((it ? FRAME_WINDOW_P (it->f) : frame_window_p)
  6172                       && valid_image_p (value))
  6173 #endif /* not HAVE_WINDOW_SYSTEM */
  6174              || (CONSP (value) && EQ (XCAR (value), Qspace))
  6175              || ((it ? FRAME_WINDOW_P (it->f) : frame_window_p)
  6176                  && valid_xwidget_spec_p (value)));
  6177 
  6178   if (valid_p && display_replaced == 0)
  6179     {
  6180       int retval = 1;
  6181 
  6182       if (!it)
  6183         {
  6184           /* Callers need to know whether the display spec is any kind
  6185              of `(space ...)' spec that is about to affect text-area
  6186              display.  */
  6187           if (CONSP (value) && EQ (XCAR (value), Qspace) && NILP (location))
  6188             retval = 2;
  6189           return retval;
  6190         }
  6191 
  6192       /* Save current settings of IT so that we can restore them
  6193          when we are finished with the glyph property value.  */
  6194       push_it (it, position);
  6195       it->from_overlay = overlay;
  6196       it->from_disp_prop_p = true;
  6197 
  6198       if (NILP (location))
  6199         it->area = TEXT_AREA;
  6200       else if (EQ (location, Qleft_margin))
  6201         it->area = LEFT_MARGIN_AREA;
  6202       else
  6203         it->area = RIGHT_MARGIN_AREA;
  6204 
  6205       if (STRINGP (value))
  6206         {
  6207           it->string = value;
  6208           it->multibyte_p = STRING_MULTIBYTE (it->string);
  6209           it->current.overlay_string_index = -1;
  6210           IT_STRING_CHARPOS (*it) = IT_STRING_BYTEPOS (*it) = 0;
  6211           it->end_charpos = it->string_nchars = SCHARS (it->string);
  6212           it->method = GET_FROM_STRING;
  6213           it->stop_charpos = 0;
  6214           it->prev_stop = 0;
  6215           it->base_level_stop = 0;
  6216           it->string_from_display_prop_p = true;
  6217           it->cmp_it.id = -1;
  6218           /* Say that we haven't consumed the characters with
  6219              `display' property yet.  The call to pop_it in
  6220              set_iterator_to_next will clean this up.  */
  6221           if (BUFFERP (object))
  6222             *position = start_pos;
  6223 
  6224           /* Force paragraph direction to be that of the parent
  6225              object.  If the parent object's paragraph direction is
  6226              not yet determined, default to L2R.  */
  6227           if (it->bidi_p && it->bidi_it.paragraph_dir == R2L)
  6228             it->paragraph_embedding = it->bidi_it.paragraph_dir;
  6229           else
  6230             it->paragraph_embedding = L2R;
  6231 
  6232           /* Set up the bidi iterator for this display string.  */
  6233           if (it->bidi_p)
  6234             {
  6235               it->bidi_it.string.lstring = it->string;
  6236               it->bidi_it.string.s = NULL;
  6237               it->bidi_it.string.schars = it->end_charpos;
  6238               it->bidi_it.string.bufpos = bufpos;
  6239               it->bidi_it.string.from_disp_str = true;
  6240               it->bidi_it.string.unibyte = !it->multibyte_p;
  6241               it->bidi_it.w = it->w;
  6242               bidi_init_it (0, 0, FRAME_WINDOW_P (it->f), &it->bidi_it);
  6243             }
  6244         }
  6245       else if (CONSP (value) && EQ (XCAR (value), Qspace))
  6246         {
  6247           it->method = GET_FROM_STRETCH;
  6248           it->object = value;
  6249           *position = it->position = start_pos;
  6250           retval = 1 + (it->area == TEXT_AREA);
  6251         }
  6252       else if (valid_xwidget_spec_p (value))
  6253         {
  6254           it->what = IT_XWIDGET;
  6255           it->method = GET_FROM_XWIDGET;
  6256           it->position = start_pos;
  6257           it->object = NILP (object) ? it->w->contents : object;
  6258           *position = start_pos;
  6259           it->xwidget = lookup_xwidget (value);
  6260         }
  6261 #ifdef HAVE_WINDOW_SYSTEM
  6262       else
  6263         {
  6264           specpdl_ref count = SPECPDL_INDEX ();
  6265 
  6266           it->what = IT_IMAGE;
  6267           /* Don't allow quitting from lookup_image, for when we are
  6268              displaying a non-selected window, and the buffer's point
  6269              was temporarily moved to the window-point.  */
  6270           specbind (Qinhibit_quit, Qt);
  6271           it->image_id = lookup_image (it->f, value, it->face_id);
  6272           unbind_to (count, Qnil);
  6273           it->position = start_pos;
  6274           it->object = NILP (object) ? it->w->contents : object;
  6275           it->method = GET_FROM_IMAGE;
  6276 
  6277           /* Say that we haven't consumed the characters with
  6278              `display' property yet.  The call to pop_it in
  6279              set_iterator_to_next will clean this up.  */
  6280           *position = start_pos;
  6281         }
  6282 #endif /* HAVE_WINDOW_SYSTEM */
  6283 
  6284       return retval;
  6285     }
  6286 
  6287   /* Invalid property or property not supported.  Restore
  6288      POSITION to what it was before.  */
  6289   *position = start_pos;
  6290   return 0;
  6291 }
  6292 
  6293 /* Check if PROP is a display property value whose text should be
  6294    treated as intangible.  OVERLAY is the overlay from which PROP
  6295    came, or nil if it came from a text property.  CHARPOS and BYTEPOS
  6296    specify the buffer position covered by PROP.  */
  6297 
  6298 bool
  6299 display_prop_intangible_p (Lisp_Object prop, Lisp_Object overlay,
  6300                            ptrdiff_t charpos, ptrdiff_t bytepos)
  6301 {
  6302   bool frame_window_p = FRAME_WINDOW_P (XFRAME (selected_frame));
  6303   struct text_pos position;
  6304 
  6305   SET_TEXT_POS (position, charpos, bytepos);
  6306   return (handle_display_spec (NULL, prop, Qnil, overlay,
  6307                                &position, charpos, frame_window_p)
  6308           != 0);
  6309 }
  6310 
  6311 
  6312 /* Return true if PROP is a display sub-property value containing STRING.
  6313 
  6314    Implementation note: this and the following function are really
  6315    special cases of handle_display_spec and
  6316    handle_single_display_spec, and should ideally use the same code.
  6317    Until they do, these two pairs must be consistent and must be
  6318    modified in sync.  */
  6319 
  6320 static bool
  6321 single_display_spec_string_p (Lisp_Object prop, Lisp_Object string)
  6322 {
  6323   if (EQ (string, prop))
  6324     return true;
  6325 
  6326   /* Skip over `when FORM'.  */
  6327   if (CONSP (prop) && EQ (XCAR (prop), Qwhen))
  6328     {
  6329       prop = XCDR (prop);
  6330       if (!CONSP (prop))
  6331         return false;
  6332       /* Actually, the condition following `when' should be eval'ed,
  6333          like handle_single_display_spec does, and we should return
  6334          false if it evaluates to nil.  However, this function is
  6335          called only when the buffer was already displayed and some
  6336          glyph in the glyph matrix was found to come from a display
  6337          string.  Therefore, the condition was already evaluated, and
  6338          the result was non-nil, otherwise the display string wouldn't
  6339          have been displayed and we would have never been called for
  6340          this property.  Thus, we can skip the evaluation and assume
  6341          its result is non-nil.  */
  6342       prop = XCDR (prop);
  6343     }
  6344 
  6345   if (CONSP (prop))
  6346     /* Skip over `margin LOCATION'.  */
  6347     if (EQ (XCAR (prop), Qmargin))
  6348       {
  6349         prop = XCDR (prop);
  6350         if (!CONSP (prop))
  6351           return false;
  6352 
  6353         prop = XCDR (prop);
  6354         if (!CONSP (prop))
  6355           return false;
  6356       }
  6357 
  6358   return EQ (prop, string) || (CONSP (prop) && EQ (XCAR (prop), string));
  6359 }
  6360 
  6361 
  6362 /* Return true if STRING appears in the `display' property PROP.  */
  6363 
  6364 static bool
  6365 display_prop_string_p (Lisp_Object prop, Lisp_Object string)
  6366 {
  6367   if (CONSP (prop)
  6368       && !EQ (XCAR (prop), Qwhen)
  6369       && !(CONSP (XCAR (prop)) && EQ (Qmargin, XCAR (XCAR (prop)))))
  6370     {
  6371       /* A list of sub-properties.  */
  6372       while (CONSP (prop))
  6373         {
  6374           if (single_display_spec_string_p (XCAR (prop), string))
  6375             return true;
  6376           prop = XCDR (prop);
  6377         }
  6378     }
  6379   else if (VECTORP (prop))
  6380     {
  6381       /* A vector of sub-properties.  */
  6382       ptrdiff_t i;
  6383       for (i = 0; i < ASIZE (prop); ++i)
  6384         if (single_display_spec_string_p (AREF (prop, i), string))
  6385           return true;
  6386     }
  6387   else
  6388     return single_display_spec_string_p (prop, string);
  6389 
  6390   return false;
  6391 }
  6392 
  6393 /* Look for STRING in overlays and text properties in the current
  6394    buffer, between character positions FROM and TO (excluding TO).
  6395    BACK_P means look back (in this case, TO is supposed to be
  6396    less than FROM).
  6397    Value is the first character position where STRING was found, or
  6398    zero if it wasn't found before hitting TO.
  6399 
  6400    This function may only use code that doesn't eval because it is
  6401    called asynchronously from note_mouse_highlight.  */
  6402 
  6403 static ptrdiff_t
  6404 string_buffer_position_lim (Lisp_Object string,
  6405                             ptrdiff_t from, ptrdiff_t to, bool back_p)
  6406 {
  6407   Lisp_Object limit, prop, pos;
  6408   bool found = false;
  6409 
  6410   pos = make_fixnum (max (from, BEGV));
  6411 
  6412   if (!back_p)  /* looking forward */
  6413     {
  6414       limit = make_fixnum (min (to, ZV));
  6415       while (!found && !EQ (pos, limit))
  6416         {
  6417           prop = Fget_char_property (pos, Qdisplay, Qnil);
  6418           if (!NILP (prop) && display_prop_string_p (prop, string))
  6419             found = true;
  6420           else
  6421             pos = Fnext_single_char_property_change (pos, Qdisplay, Qnil,
  6422                                                      limit);
  6423         }
  6424     }
  6425   else          /* looking back */
  6426     {
  6427       limit = make_fixnum (max (to, BEGV));
  6428       while (!found && !EQ (pos, limit))
  6429         {
  6430           prop = Fget_char_property (pos, Qdisplay, Qnil);
  6431           if (!NILP (prop) && display_prop_string_p (prop, string))
  6432             found = true;
  6433           else
  6434             pos = Fprevious_single_char_property_change (pos, Qdisplay, Qnil,
  6435                                                          limit);
  6436         }
  6437     }
  6438 
  6439   return found ? XFIXNUM (pos) : 0;
  6440 }
  6441 
  6442 /* Determine which buffer position in current buffer STRING comes from.
  6443    AROUND_CHARPOS is an approximate position where it could come from.
  6444    Value is the buffer position or 0 if it couldn't be determined.
  6445 
  6446    This function is necessary because we don't record buffer positions
  6447    in glyphs generated from strings (to keep struct glyph small).
  6448    This function may only use code that doesn't eval because it is
  6449    called asynchronously from note_mouse_highlight.  */
  6450 
  6451 static ptrdiff_t
  6452 string_buffer_position (Lisp_Object string, ptrdiff_t around_charpos)
  6453 {
  6454   const int MAX_DISTANCE = 1000;
  6455   ptrdiff_t forward_limit = min (around_charpos + MAX_DISTANCE, ZV);
  6456   ptrdiff_t found = string_buffer_position_lim (string, around_charpos,
  6457                                                 forward_limit, false);
  6458 
  6459   if (!found)
  6460     {
  6461       ptrdiff_t backward_limit = max (around_charpos - MAX_DISTANCE, BEGV);
  6462       found = string_buffer_position_lim (string, around_charpos,
  6463                                           backward_limit, true);
  6464     }
  6465   return found;
  6466 }
  6467 
  6468 
  6469 
  6470 /***********************************************************************
  6471                         `composition' property
  6472  ***********************************************************************/
  6473 
  6474 /* Set up iterator IT from `composition' property at its current
  6475    position.  Called from handle_stop.  */
  6476 
  6477 static enum prop_handled
  6478 handle_composition_prop (struct it *it)
  6479 {
  6480   Lisp_Object prop, string;
  6481   ptrdiff_t pos, pos_byte, start, end;
  6482 
  6483   if (STRINGP (it->string))
  6484     {
  6485       unsigned char *s;
  6486 
  6487       pos = IT_STRING_CHARPOS (*it);
  6488       pos_byte = IT_STRING_BYTEPOS (*it);
  6489       string = it->string;
  6490       s = SDATA (string) + pos_byte;
  6491       if (STRING_MULTIBYTE (string))
  6492         it->c = STRING_CHAR (s);
  6493       else
  6494         it->c = *s;
  6495     }
  6496   else
  6497     {
  6498       pos = IT_CHARPOS (*it);
  6499       pos_byte = IT_BYTEPOS (*it);
  6500       string = Qnil;
  6501       it->c = FETCH_CHAR (pos_byte);
  6502     }
  6503 
  6504   /* If there's a valid composition and point is not inside of the
  6505      composition (in the case that the composition is from the current
  6506      buffer), draw a glyph composed from the composition components.  */
  6507   if (find_composition (pos, -1, &start, &end, &prop, string)
  6508       && composition_valid_p (start, end, prop)
  6509       && (STRINGP (it->string) || (PT <= start || PT >= end)))
  6510     {
  6511       if (start < pos)
  6512         /* As we can't handle this situation (perhaps font-lock added
  6513            a new composition), we just return here hoping that next
  6514            redisplay will detect this composition much earlier.  */
  6515         return HANDLED_NORMALLY;
  6516       if (start != pos)
  6517         {
  6518           if (STRINGP (it->string))
  6519             pos_byte = string_char_to_byte (it->string, start);
  6520           else
  6521             pos_byte = CHAR_TO_BYTE (start);
  6522         }
  6523       it->cmp_it.id = get_composition_id (start, pos_byte, end - start,
  6524                                                prop, string);
  6525 
  6526       if (it->cmp_it.id >= 0)
  6527         {
  6528           it->cmp_it.ch = -1;
  6529           it->cmp_it.nchars = COMPOSITION_LENGTH (prop);
  6530           it->cmp_it.nglyphs = -1;
  6531         }
  6532     }
  6533 
  6534   return HANDLED_NORMALLY;
  6535 }
  6536 
  6537 
  6538 
  6539 /***********************************************************************
  6540                            Overlay strings
  6541  ***********************************************************************/
  6542 
  6543 /* The following structure is used to record overlay strings for
  6544    later sorting in load_overlay_strings.  */
  6545 
  6546 struct overlay_entry
  6547 {
  6548   Lisp_Object overlay;
  6549   Lisp_Object string;
  6550   EMACS_INT priority;
  6551   bool after_string_p;
  6552 };
  6553 
  6554 
  6555 /* Set up iterator IT from overlay strings at its current position.
  6556    Called from handle_stop.  */
  6557 
  6558 static enum prop_handled
  6559 handle_overlay_change (struct it *it)
  6560 {
  6561   if (!STRINGP (it->string) && get_overlay_strings (it, 0))
  6562     return HANDLED_RECOMPUTE_PROPS;
  6563   else
  6564     return HANDLED_NORMALLY;
  6565 }
  6566 
  6567 
  6568 /* Set up the next overlay string for delivery by IT, if there is an
  6569    overlay string to deliver.  Called by set_iterator_to_next when the
  6570    end of the current overlay string is reached.  If there are more
  6571    overlay strings to display, IT->string and
  6572    IT->current.overlay_string_index are set appropriately here.
  6573    Otherwise IT->string is set to nil.  */
  6574 
  6575 static void
  6576 next_overlay_string (struct it *it)
  6577 {
  6578   ++it->current.overlay_string_index;
  6579   if (it->current.overlay_string_index == it->n_overlay_strings)
  6580     {
  6581       /* No more overlay strings.  Restore IT's settings to what
  6582          they were before overlay strings were processed, and
  6583          continue to deliver from current_buffer.  */
  6584 
  6585       it->ellipsis_p = it->stack[it->sp - 1].display_ellipsis_p;
  6586       pop_it (it);
  6587       eassert (it->sp > 0
  6588                || (NILP (it->string)
  6589                    && it->method == GET_FROM_BUFFER
  6590                    && it->stop_charpos >= BEGV
  6591                    && it->stop_charpos <= it->end_charpos));
  6592       it->current.overlay_string_index = -1;
  6593       it->n_overlay_strings = 0;
  6594       /* If there's an empty display string on the stack, pop the
  6595          stack, to resync the bidi iterator with IT's position.  Such
  6596          empty strings are pushed onto the stack in
  6597          get_overlay_strings_1.  */
  6598       if (it->sp > 0 && STRINGP (it->string) && !SCHARS (it->string))
  6599         pop_it (it);
  6600 
  6601       /* Since we've exhausted overlay strings at this buffer
  6602          position, set the flag to ignore overlays until we move to
  6603          another position.  (The flag will be reset in
  6604          next_element_from_buffer.)  But don't do that if the overlay
  6605          strings were loaded at position other than the current one,
  6606          which could happen if we called pop_it above, or if the
  6607          overlay strings were loaded by handle_invisible_prop at the
  6608          beginning of invisible text.  */
  6609       if (it->overlay_strings_charpos == IT_CHARPOS (*it))
  6610         it->ignore_overlay_strings_at_pos_p = true;
  6611 
  6612       /* If we're at the end of the buffer, record that we have
  6613          processed the overlay strings there already, so that
  6614          next_element_from_buffer doesn't try it again.  */
  6615       if (NILP (it->string)
  6616           && IT_CHARPOS (*it) >= it->end_charpos
  6617           && it->overlay_strings_charpos >= it->end_charpos)
  6618         it->overlay_strings_at_end_processed_p = true;
  6619       /* Note: we reset overlay_strings_charpos only here, to make
  6620          sure the just-processed overlays were indeed at EOB.
  6621          Otherwise, overlays on text with invisible text property,
  6622          which are processed with IT's position past the invisible
  6623          text, might fool us into thinking the overlays at EOB were
  6624          already processed (linum-mode can cause this, for
  6625          example).  */
  6626       it->overlay_strings_charpos = -1;
  6627     }
  6628   else
  6629     {
  6630       /* There are more overlay strings to process.  If
  6631          IT->current.overlay_string_index has advanced to a position
  6632          where we must load IT->overlay_strings with more strings, do
  6633          it.  We must load at the IT->overlay_strings_charpos where
  6634          IT->n_overlay_strings was originally computed; when invisible
  6635          text is present, this might not be IT_CHARPOS (Bug#7016).  */
  6636       int i = it->current.overlay_string_index % OVERLAY_STRING_CHUNK_SIZE;
  6637 
  6638       if (it->current.overlay_string_index && i == 0)
  6639         load_overlay_strings (it, it->overlay_strings_charpos);
  6640 
  6641       /* Initialize IT to deliver display elements from the overlay
  6642          string.  */
  6643       it->string = it->overlay_strings[i];
  6644       it->multibyte_p = STRING_MULTIBYTE (it->string);
  6645       SET_TEXT_POS (it->current.string_pos, 0, 0);
  6646       it->method = GET_FROM_STRING;
  6647       it->stop_charpos = 0;
  6648       it->end_charpos = SCHARS (it->string);
  6649       if (it->cmp_it.stop_pos >= 0)
  6650         it->cmp_it.stop_pos = 0;
  6651       it->prev_stop = 0;
  6652       it->base_level_stop = 0;
  6653 
  6654       /* Set up the bidi iterator for this overlay string.  */
  6655       if (it->bidi_p)
  6656         {
  6657           it->bidi_it.string.lstring = it->string;
  6658           it->bidi_it.string.s = NULL;
  6659           it->bidi_it.string.schars = SCHARS (it->string);
  6660           it->bidi_it.string.bufpos = it->overlay_strings_charpos;
  6661           it->bidi_it.string.from_disp_str = it->string_from_display_prop_p;
  6662           it->bidi_it.string.unibyte = !it->multibyte_p;
  6663           it->bidi_it.w = it->w;
  6664           bidi_init_it (0, 0, FRAME_WINDOW_P (it->f), &it->bidi_it);
  6665         }
  6666     }
  6667 
  6668   CHECK_IT (it);
  6669 }
  6670 
  6671 
  6672 /* Compare two overlay_entry structures E1 and E2.  Used as a
  6673    comparison function for qsort in load_overlay_strings.  Overlay
  6674    strings for the same position are sorted so that
  6675 
  6676    1. All after-strings come in front of before-strings, except
  6677    when they come from the same overlay.
  6678 
  6679    2. Within after-strings, strings are sorted so that overlay strings
  6680    from overlays with higher priorities come first.
  6681 
  6682    2. Within before-strings, strings are sorted so that overlay
  6683    strings from overlays with higher priorities come last.
  6684 
  6685    Value is analogous to strcmp.  */
  6686 
  6687 
  6688 static int
  6689 compare_overlay_entries (const void *e1, const void *e2)
  6690 {
  6691   struct overlay_entry const *entry1 = e1;
  6692   struct overlay_entry const *entry2 = e2;
  6693   int result;
  6694 
  6695   if (entry1->after_string_p != entry2->after_string_p)
  6696     {
  6697       /* Let after-strings appear in front of before-strings if
  6698          they come from different overlays.  */
  6699       if (EQ (entry1->overlay, entry2->overlay))
  6700         result = entry1->after_string_p ? 1 : -1;
  6701       else
  6702         result = entry1->after_string_p ? -1 : 1;
  6703     }
  6704   else if (entry1->priority != entry2->priority)
  6705     {
  6706       if (entry1->after_string_p)
  6707         /* After-strings sorted in order of decreasing priority.  */
  6708         result = entry2->priority < entry1->priority ? -1 : 1;
  6709       else
  6710         /* Before-strings sorted in order of increasing priority.  */
  6711         result = entry1->priority < entry2->priority ? -1 : 1;
  6712     }
  6713   else
  6714     result = 0;
  6715 
  6716   return result;
  6717 }
  6718 
  6719 
  6720 /* Load the vector IT->overlay_strings with overlay strings from IT's
  6721    current buffer position, or from CHARPOS if that is > 0.  Set
  6722    IT->n_overlays to the total number of overlay strings found.
  6723 
  6724    Overlay strings are processed OVERLAY_STRING_CHUNK_SIZE strings at
  6725    a time.  On entry into load_overlay_strings,
  6726    IT->current.overlay_string_index gives the number of overlay
  6727    strings that have already been loaded by previous calls to this
  6728    function.
  6729 
  6730    IT->add_overlay_start contains an additional overlay start
  6731    position to consider for taking overlay strings from, if non-zero.
  6732    This position comes into play when the overlay has an `invisible'
  6733    property, and both before and after-strings.  When we've skipped to
  6734    the end of the overlay, because of its `invisible' property, we
  6735    nevertheless want its before-string to appear.
  6736    IT->add_overlay_start will contain the overlay start position
  6737    in this case.
  6738 
  6739    Overlay strings are sorted so that after-string strings come in
  6740    front of before-string strings.  Within before and after-strings,
  6741    strings are sorted by overlay priority.  See also function
  6742    compare_overlay_entries.  */
  6743 
  6744 static void
  6745 load_overlay_strings (struct it *it, ptrdiff_t charpos)
  6746 {
  6747   ptrdiff_t n = 0;
  6748   struct overlay_entry entriesbuf[20];
  6749   ptrdiff_t size = ARRAYELTS (entriesbuf);
  6750   struct overlay_entry *entries = entriesbuf;
  6751   struct itree_node *node;
  6752 
  6753   USE_SAFE_ALLOCA;
  6754 
  6755   if (charpos <= 0)
  6756     charpos = IT_CHARPOS (*it);
  6757 
  6758   /* Append the overlay string STRING of overlay OVERLAY to vector
  6759      `entries' which has size `size' and currently contains `n'
  6760      elements.  AFTER_P means STRING is an after-string of
  6761      OVERLAY.  */
  6762 #define RECORD_OVERLAY_STRING(OVERLAY, STRING, AFTER_P)                 \
  6763   do                                                                    \
  6764     {                                                                   \
  6765       Lisp_Object priority;                                             \
  6766                                                                         \
  6767       if (n == size)                                                    \
  6768         {                                                               \
  6769           struct overlay_entry *old = entries;                          \
  6770           SAFE_NALLOCA (entries, 2, size);                              \
  6771           memcpy (entries, old, size * sizeof *entries);                \
  6772           size *= 2;                                                    \
  6773         }                                                               \
  6774                                                                         \
  6775       entries[n].string = (STRING);                                     \
  6776       entries[n].overlay = (OVERLAY);                                   \
  6777       priority = Foverlay_get ((OVERLAY), Qpriority);                   \
  6778       entries[n].priority = FIXNUMP (priority) ? XFIXNUM (priority) : 0;  \
  6779       entries[n].after_string_p = (AFTER_P);                            \
  6780       ++n;                                                              \
  6781     }                                                                   \
  6782   while (false)
  6783 
  6784 
  6785   /* Process overlays.  */
  6786   ITREE_FOREACH (node, current_buffer->overlays, charpos - 1, charpos + 1, DESCENDING)
  6787     {
  6788       Lisp_Object overlay = node->data;
  6789       eassert (OVERLAYP (overlay));
  6790       ptrdiff_t start = node->begin;
  6791       ptrdiff_t end = node->end;
  6792 
  6793       /* Skip this overlay if it doesn't start or end at IT's current
  6794          position.  */
  6795       if (end != charpos && start != charpos)
  6796         continue;
  6797 
  6798       /* Skip this overlay if it doesn't apply to IT->w.  */
  6799       Lisp_Object window = Foverlay_get (overlay, Qwindow);
  6800       if (WINDOWP (window) && XWINDOW (window) != it->w)
  6801         continue;
  6802 
  6803       /* If the text ``under'' the overlay is invisible, both before-
  6804          and after-strings from this overlay are visible; start and
  6805          end position are indistinguishable.  */
  6806       Lisp_Object invisible = Foverlay_get (overlay, Qinvisible);
  6807       int invis = TEXT_PROP_MEANS_INVISIBLE (invisible);
  6808 
  6809       /* If overlay has a non-empty before-string, record it.  */
  6810       Lisp_Object str;
  6811       if ((start == charpos || (end == charpos && invis != 0))
  6812           && (str = Foverlay_get (overlay, Qbefore_string), STRINGP (str))
  6813           && SCHARS (str))
  6814         RECORD_OVERLAY_STRING (overlay, str, false);
  6815 
  6816       /* If overlay has a non-empty after-string, record it.  */
  6817       if ((end == charpos || (start == charpos && invis != 0))
  6818           && (str = Foverlay_get (overlay, Qafter_string), STRINGP (str))
  6819           && SCHARS (str))
  6820         RECORD_OVERLAY_STRING (overlay, str, true);
  6821     }
  6822 
  6823 #undef RECORD_OVERLAY_STRING
  6824 
  6825   /* Sort entries.  */
  6826   if (n > 1)
  6827     qsort (entries, n, sizeof *entries, compare_overlay_entries);
  6828 
  6829   /* Record number of overlay strings, and where we computed it.  */
  6830   it->n_overlay_strings = n;
  6831   it->overlay_strings_charpos = charpos;
  6832 
  6833   /* IT->current.overlay_string_index is the number of overlay strings
  6834      that have already been consumed by IT.  Copy some of the
  6835      remaining overlay strings to IT->overlay_strings.  */
  6836   ptrdiff_t j = it->current.overlay_string_index;
  6837   for (ptrdiff_t i = 0; i < OVERLAY_STRING_CHUNK_SIZE && j < n; i++, j++)
  6838     {
  6839       it->overlay_strings[i] = entries[j].string;
  6840       it->string_overlays[i] = entries[j].overlay;
  6841     }
  6842 
  6843   CHECK_IT (it);
  6844   SAFE_FREE ();
  6845 }
  6846 
  6847 
  6848 /* Get the first chunk of overlay strings at IT's current buffer
  6849    position, or at CHARPOS if that is > 0.  Value is true if at
  6850    least one overlay string was found.  */
  6851 
  6852 static bool
  6853 get_overlay_strings_1 (struct it *it, ptrdiff_t charpos, bool compute_stop_p)
  6854 {
  6855   /* Get the first OVERLAY_STRING_CHUNK_SIZE overlay strings to
  6856      process.  This fills IT->overlay_strings with strings, and sets
  6857      IT->n_overlay_strings to the total number of strings to process.
  6858      IT->pos.overlay_string_index has to be set temporarily to zero
  6859      because load_overlay_strings needs this; it must be set to -1
  6860      when no overlay strings are found because a zero value would
  6861      indicate a position in the first overlay string.  */
  6862   it->current.overlay_string_index = 0;
  6863   load_overlay_strings (it, charpos);
  6864 
  6865   /* If we found overlay strings, set up IT to deliver display
  6866      elements from the first one.  Otherwise set up IT to deliver
  6867      from current_buffer.  */
  6868   if (it->n_overlay_strings)
  6869     {
  6870       /* Make sure we know settings in current_buffer, so that we can
  6871          restore meaningful values when we're done with the overlay
  6872          strings.  */
  6873       if (compute_stop_p)
  6874         compute_stop_pos (it);
  6875       eassert (it->face_id >= 0);
  6876 
  6877       /* Save IT's settings.  They are restored after all overlay
  6878          strings have been processed.  */
  6879       eassert (!compute_stop_p || it->sp == 0);
  6880 
  6881       /* When called from handle_stop, there might be an empty display
  6882          string loaded.  In that case, don't bother saving it.  But
  6883          don't use this optimization with the bidi iterator, since we
  6884          need the corresponding pop_it call to resync the bidi
  6885          iterator's position with IT's position, after we are done
  6886          with the overlay strings.  (The corresponding call to pop_it
  6887          in case of an empty display string is in
  6888          next_overlay_string.)  */
  6889       if (!(!it->bidi_p
  6890             && STRINGP (it->string) && !SCHARS (it->string)))
  6891         push_it (it, NULL);
  6892 
  6893       /* Set up IT to deliver display elements from the first overlay
  6894          string.  */
  6895       IT_STRING_CHARPOS (*it) = IT_STRING_BYTEPOS (*it) = 0;
  6896       it->string = it->overlay_strings[0];
  6897       it->from_overlay = Qnil;
  6898       it->stop_charpos = 0;
  6899       eassert (STRINGP (it->string));
  6900       it->end_charpos = SCHARS (it->string);
  6901       it->prev_stop = 0;
  6902       it->base_level_stop = 0;
  6903       it->multibyte_p = STRING_MULTIBYTE (it->string);
  6904       it->method = GET_FROM_STRING;
  6905       it->from_disp_prop_p = 0;
  6906       it->cmp_it.id = -1;
  6907 
  6908       /* Force paragraph direction to be that of the parent
  6909          buffer.  */
  6910       if (it->bidi_p && it->bidi_it.paragraph_dir == R2L)
  6911         it->paragraph_embedding = it->bidi_it.paragraph_dir;
  6912       else
  6913         it->paragraph_embedding = L2R;
  6914 
  6915       /* Set up the bidi iterator for this overlay string.  */
  6916       if (it->bidi_p)
  6917         {
  6918           ptrdiff_t pos = (charpos > 0 ? charpos : IT_CHARPOS (*it));
  6919 
  6920           it->bidi_it.string.lstring = it->string;
  6921           it->bidi_it.string.s = NULL;
  6922           it->bidi_it.string.schars = SCHARS (it->string);
  6923           it->bidi_it.string.bufpos = pos;
  6924           it->bidi_it.string.from_disp_str = it->string_from_display_prop_p;
  6925           it->bidi_it.string.unibyte = !it->multibyte_p;
  6926           it->bidi_it.w = it->w;
  6927           bidi_init_it (0, 0, FRAME_WINDOW_P (it->f), &it->bidi_it);
  6928         }
  6929       return true;
  6930     }
  6931 
  6932   it->current.overlay_string_index = -1;
  6933   return false;
  6934 }
  6935 
  6936 static bool
  6937 get_overlay_strings (struct it *it, ptrdiff_t charpos)
  6938 {
  6939   it->string = Qnil;
  6940   it->method = GET_FROM_BUFFER;
  6941 
  6942   get_overlay_strings_1 (it, charpos, true);
  6943 
  6944   CHECK_IT (it);
  6945 
  6946   /* Value is true if we found at least one overlay string.  */
  6947   return STRINGP (it->string);
  6948 }
  6949 
  6950 
  6951 
  6952 /***********************************************************************
  6953                       Saving and restoring state
  6954  ***********************************************************************/
  6955 
  6956 /* Save current settings of IT on IT->stack.  Called, for example,
  6957    before setting up IT for an overlay string, to be able to restore
  6958    IT's settings to what they were after the overlay string has been
  6959    processed.  If POSITION is non-NULL, it is the position to save on
  6960    the stack instead of IT->position.  */
  6961 
  6962 static void
  6963 push_it (struct it *it, struct text_pos *position)
  6964 {
  6965   struct iterator_stack_entry *p;
  6966 
  6967   eassert (it->sp < IT_STACK_SIZE);
  6968   p = it->stack + it->sp;
  6969 
  6970   p->stop_charpos = it->stop_charpos;
  6971   p->prev_stop = it->prev_stop;
  6972   p->base_level_stop = it->base_level_stop;
  6973   p->cmp_it = it->cmp_it;
  6974   eassert (it->face_id >= 0);
  6975   p->face_id = it->face_id;
  6976   p->string = it->string;
  6977   p->method = it->method;
  6978   p->from_overlay = it->from_overlay;
  6979   switch (p->method)
  6980     {
  6981     case GET_FROM_IMAGE:
  6982       p->u.image.object = it->object;
  6983       p->u.image.image_id = it->image_id;
  6984       p->u.image.slice = it->slice;
  6985       break;
  6986     case GET_FROM_STRETCH:
  6987       p->u.stretch.object = it->object;
  6988       break;
  6989     case GET_FROM_XWIDGET:
  6990       p->u.xwidget.object = it->object;
  6991       break;
  6992     case GET_FROM_BUFFER:
  6993     case GET_FROM_DISPLAY_VECTOR:
  6994     case GET_FROM_STRING:
  6995     case GET_FROM_C_STRING:
  6996       break;
  6997     default:
  6998       emacs_abort ();
  6999     }
  7000   p->position = position ? *position : it->position;
  7001   p->current = it->current;
  7002   p->end_charpos = it->end_charpos;
  7003   p->string_nchars = it->string_nchars;
  7004   p->area = it->area;
  7005   p->multibyte_p = it->multibyte_p;
  7006   p->avoid_cursor_p = it->avoid_cursor_p;
  7007   p->space_width = it->space_width;
  7008   p->font_height = it->font_height;
  7009   p->voffset = it->voffset;
  7010   p->string_from_display_prop_p = it->string_from_display_prop_p;
  7011   p->string_from_prefix_prop_p = it->string_from_prefix_prop_p;
  7012   p->display_ellipsis_p = false;
  7013   p->line_wrap = it->line_wrap;
  7014   p->bidi_p = it->bidi_p;
  7015   p->paragraph_embedding = it->paragraph_embedding;
  7016   p->from_disp_prop_p = it->from_disp_prop_p;
  7017   ++it->sp;
  7018 
  7019   /* Save the state of the bidi iterator as well. */
  7020   if (it->bidi_p)
  7021     bidi_push_it (&it->bidi_it);
  7022 }
  7023 
  7024 static void
  7025 iterate_out_of_display_property (struct it *it)
  7026 {
  7027   bool buffer_p = !STRINGP (it->string);
  7028   ptrdiff_t eob = (buffer_p ? ZV : it->end_charpos);
  7029   ptrdiff_t bob = (buffer_p ? BEGV : 0);
  7030 
  7031   eassert (eob >= CHARPOS (it->position) && CHARPOS (it->position) >= bob);
  7032 
  7033   /* Maybe initialize paragraph direction.  If we are at the beginning
  7034      of a new paragraph, next_element_from_buffer may not have a
  7035      chance to do that.  */
  7036   if (it->bidi_it.first_elt && it->bidi_it.charpos < eob)
  7037     bidi_paragraph_init (it->paragraph_embedding, &it->bidi_it, true);
  7038   /* prev_stop can be zero, so check against BEGV as well.  */
  7039   while (it->bidi_it.charpos >= bob
  7040          && it->prev_stop <= it->bidi_it.charpos
  7041          && it->bidi_it.charpos < CHARPOS (it->position)
  7042          && it->bidi_it.charpos < eob)
  7043     bidi_move_to_visually_next (&it->bidi_it);
  7044   /* Record the stop_pos we just crossed, for when we cross it
  7045      back, maybe.  */
  7046   if (it->bidi_it.charpos > CHARPOS (it->position))
  7047     it->prev_stop = CHARPOS (it->position);
  7048   /* If we ended up not where pop_it put us, resync IT's
  7049      positional members with the bidi iterator. */
  7050   if (it->bidi_it.charpos != CHARPOS (it->position))
  7051     SET_TEXT_POS (it->position, it->bidi_it.charpos, it->bidi_it.bytepos);
  7052   if (buffer_p)
  7053     it->current.pos = it->position;
  7054   else
  7055     it->current.string_pos = it->position;
  7056 }
  7057 
  7058 /* Restore the IT->face_box_p flag, since it could have been
  7059    overwritten by the face of the object that we just finished
  7060    displaying.  Also, set the IT->start_of_box_run_p flag if the
  7061    change in faces requires that.  */
  7062 static void
  7063 restore_face_box_flags (struct it *it, int prev_face_id)
  7064 {
  7065   struct face *face = FACE_FROM_ID_OR_NULL (it->f, it->face_id);
  7066 
  7067   if (face)
  7068     {
  7069       struct face *prev_face = FACE_FROM_ID_OR_NULL (it->f, prev_face_id);
  7070 
  7071       if (!(it->start_of_box_run_p && prev_face && prev_face->box))
  7072         it->start_of_box_run_p = (face->box != FACE_NO_BOX
  7073                                   && (prev_face == NULL
  7074                                       || prev_face->box == FACE_NO_BOX));
  7075       it->face_box_p = face->box != FACE_NO_BOX;
  7076     }
  7077 }
  7078 
  7079 /* Restore IT's settings from IT->stack.  Called, for example, when no
  7080    more overlay strings must be processed, and we return to delivering
  7081    display elements from a buffer, or when the end of a string from a
  7082    `display' property is reached and we return to delivering display
  7083    elements from an overlay string, or from a buffer.  */
  7084 
  7085 static void
  7086 pop_it (struct it *it)
  7087 {
  7088   struct iterator_stack_entry *p;
  7089   bool from_display_prop = it->from_disp_prop_p;
  7090   ptrdiff_t prev_pos = IT_CHARPOS (*it);
  7091   int prev_face_id = it->face_id;
  7092 
  7093   eassert (it->sp > 0);
  7094   --it->sp;
  7095   p = it->stack + it->sp;
  7096   it->stop_charpos = p->stop_charpos;
  7097   it->prev_stop = p->prev_stop;
  7098   it->base_level_stop = p->base_level_stop;
  7099   it->cmp_it = p->cmp_it;
  7100   it->face_id = p->face_id;
  7101   it->current = p->current;
  7102   it->position = p->position;
  7103   it->string = p->string;
  7104   it->from_overlay = p->from_overlay;
  7105   if (NILP (it->string))
  7106     SET_TEXT_POS (it->current.string_pos, -1, -1);
  7107   it->method = p->method;
  7108   switch (it->method)
  7109     {
  7110     case GET_FROM_IMAGE:
  7111       it->image_id = p->u.image.image_id;
  7112       it->object = p->u.image.object;
  7113       it->slice = p->u.image.slice;
  7114       break;
  7115     case GET_FROM_XWIDGET:
  7116       it->object = p->u.xwidget.object;
  7117       break;
  7118     case GET_FROM_STRETCH:
  7119       it->object = p->u.stretch.object;
  7120       break;
  7121     case GET_FROM_BUFFER:
  7122       {
  7123         restore_face_box_flags (it, prev_face_id);
  7124         it->object = it->w->contents;
  7125       }
  7126       break;
  7127     case GET_FROM_STRING:
  7128       {
  7129         restore_face_box_flags (it, prev_face_id);
  7130         it->object = it->string;
  7131       }
  7132       break;
  7133     case GET_FROM_DISPLAY_VECTOR:
  7134       if (it->s)
  7135         it->method = GET_FROM_C_STRING;
  7136       else if (STRINGP (it->string))
  7137         it->method = GET_FROM_STRING;
  7138       else
  7139         {
  7140           it->method = GET_FROM_BUFFER;
  7141           it->object = it->w->contents;
  7142         }
  7143       break;
  7144     case GET_FROM_C_STRING:
  7145       break;
  7146     default:
  7147       emacs_abort ();
  7148     }
  7149   it->end_charpos = p->end_charpos;
  7150   it->string_nchars = p->string_nchars;
  7151   it->area = p->area;
  7152   it->multibyte_p = p->multibyte_p;
  7153   it->avoid_cursor_p = p->avoid_cursor_p;
  7154   it->space_width = p->space_width;
  7155   it->font_height = p->font_height;
  7156   it->voffset = p->voffset;
  7157   it->string_from_display_prop_p = p->string_from_display_prop_p;
  7158   it->string_from_prefix_prop_p = p->string_from_prefix_prop_p;
  7159   it->line_wrap = p->line_wrap;
  7160   it->bidi_p = p->bidi_p;
  7161   it->paragraph_embedding = p->paragraph_embedding;
  7162   it->from_disp_prop_p = p->from_disp_prop_p;
  7163   if (it->bidi_p)
  7164     {
  7165       bidi_pop_it (&it->bidi_it);
  7166       /* Bidi-iterate until we get out of the portion of text, if any,
  7167          covered by a `display' text property or by an overlay with
  7168          `display' property.  (We cannot just jump there, because the
  7169          internal coherency of the bidi iterator state can not be
  7170          preserved across such jumps.)  We also must determine the
  7171          paragraph base direction if the overlay we just processed is
  7172          at the beginning of a new paragraph.  */
  7173       if (from_display_prop
  7174           && (it->method == GET_FROM_BUFFER || it->method == GET_FROM_STRING))
  7175         iterate_out_of_display_property (it);
  7176 
  7177       eassert ((BUFFERP (it->object)
  7178                 && IT_CHARPOS (*it) == it->bidi_it.charpos
  7179                 && IT_BYTEPOS (*it) == it->bidi_it.bytepos)
  7180                || (STRINGP (it->object)
  7181                    && IT_STRING_CHARPOS (*it) == it->bidi_it.charpos
  7182                    && IT_STRING_BYTEPOS (*it) == it->bidi_it.bytepos)
  7183                || (CONSP (it->object) && it->method == GET_FROM_STRETCH)
  7184                /* We could be in the middle of handling a list or a
  7185                   vector of several 'display' properties, in which
  7186                   case we should only verify the above conditions when
  7187                   we pop the iterator stack the last time, because
  7188                   higher stack levels cannot "iterate out of the
  7189                   display property".  */
  7190                || it->sp > 0);
  7191     }
  7192   /* If we move the iterator over text covered by a display property
  7193      to a new buffer position, any info about previously seen overlays
  7194      is no longer valid.  */
  7195   if (from_display_prop && it->sp == 0 && CHARPOS (it->position) != prev_pos)
  7196     it->ignore_overlay_strings_at_pos_p = false;
  7197 }
  7198 
  7199 
  7200 
  7201 /***********************************************************************
  7202                           Moving over lines
  7203  ***********************************************************************/
  7204 
  7205 /* Set IT's current position to the previous line start.  */
  7206 
  7207 static void
  7208 back_to_previous_line_start (struct it *it)
  7209 {
  7210   ptrdiff_t cp = IT_CHARPOS (*it), bp = IT_BYTEPOS (*it);
  7211 
  7212   dec_both (&cp, &bp);
  7213   SET_WITH_NARROWED_BEGV (it, IT_CHARPOS (*it),
  7214                           find_newline_no_quit (cp, bp, -1, &IT_BYTEPOS (*it)),
  7215                           get_small_narrowing_begv (it->w, IT_CHARPOS (*it)));
  7216 }
  7217 
  7218 /* Find in the current buffer the first display or overlay string
  7219    between STARTPOS and ENDPOS that includes embedded newlines.
  7220    Consider only overlays that apply to window W.
  7221    Value is non-zero if such a display/overlay string is found.  */
  7222 static bool
  7223 strings_with_newlines (ptrdiff_t startpos, ptrdiff_t endpos, struct window *w)
  7224 {
  7225   struct itree_node *node;
  7226   /* Process overlays.  */
  7227   ITREE_FOREACH (node, current_buffer->overlays, startpos, endpos, DESCENDING)
  7228     {
  7229       Lisp_Object overlay = node->data;
  7230       eassert (OVERLAYP (overlay));
  7231 
  7232       /* Skip this overlay if it doesn't apply to our window.  */
  7233       Lisp_Object window = Foverlay_get (overlay, Qwindow);
  7234       if (WINDOWP (window) && XWINDOW (window) != w)
  7235         continue;
  7236 
  7237       ptrdiff_t ostart = node->begin;
  7238       ptrdiff_t oend = node->end;
  7239 
  7240       /* Skip overlays that don't overlap the range.  */
  7241       if (!((startpos < oend && ostart < endpos)
  7242             || (ostart == oend
  7243                 && (startpos == oend || (endpos == ZV && oend == endpos)))))
  7244         continue;
  7245 
  7246       Lisp_Object str;
  7247       str = Foverlay_get (overlay, Qbefore_string);
  7248       if (STRINGP (str) && SCHARS (str)
  7249           && memchr (SDATA (str), '\n', SBYTES (str)))
  7250         return true;
  7251       str = Foverlay_get (overlay, Qafter_string);
  7252       if (STRINGP (str) && SCHARS (str)
  7253           && memchr (SDATA (str), '\n', SBYTES (str)))
  7254         return true;
  7255     }
  7256 
  7257   /* Check for 'display' properties whose values include strings.  */
  7258   Lisp_Object cpos = make_fixnum (startpos);
  7259   Lisp_Object limpos = make_fixnum (endpos);
  7260 
  7261   while ((cpos = Fnext_single_property_change (cpos, Qdisplay, Qnil, limpos),
  7262           !(NILP (cpos) || XFIXNAT (cpos) >= endpos)))
  7263     {
  7264       Lisp_Object spec = Fget_char_property (cpos, Qdisplay, Qnil);
  7265       Lisp_Object string = string_from_display_spec (spec);
  7266       if (STRINGP (string)
  7267           && memchr (SDATA (string), '\n', SBYTES (string)))
  7268         return true;
  7269     }
  7270 
  7271   return false;
  7272 }
  7273 
  7274 
  7275 /* Move IT to the next line start.
  7276 
  7277    Value is true if a newline was found.  Set *SKIPPED_P to true if
  7278    we skipped over part of the text (as opposed to moving the iterator
  7279    continuously over the text).  Otherwise, don't change the value
  7280    of *SKIPPED_P.
  7281 
  7282    If BIDI_IT_PREV is non-NULL, store into it the state of the bidi
  7283    iterator on the newline, if it was found.
  7284 
  7285    Newlines may come from buffer text, overlay strings, or strings
  7286    displayed via the `display' property.  That's the reason we can't
  7287    simply use find_newline_no_quit.
  7288 
  7289    Note that this function may not skip over invisible text that is so
  7290    because of text properties and immediately follows a newline.  If
  7291    it would, function reseat_at_next_visible_line_start, when called
  7292    from set_iterator_to_next, would effectively make invisible
  7293    characters following a newline part of the wrong glyph row, which
  7294    leads to wrong cursor motion.  */
  7295 
  7296 static bool
  7297 forward_to_next_line_start (struct it *it, bool *skipped_p,
  7298                             struct bidi_it *bidi_it_prev)
  7299 {
  7300   ptrdiff_t old_selective;
  7301   bool newline_found_p = false;
  7302   int n;
  7303   const int MAX_NEWLINE_DISTANCE = 500;
  7304 
  7305   /* If already on a newline, just consume it to avoid unintended
  7306      skipping over invisible text below.  */
  7307   if (it->what == IT_CHARACTER
  7308       && it->c == '\n'
  7309       && CHARPOS (it->position) == IT_CHARPOS (*it))
  7310     {
  7311       if (it->bidi_p && bidi_it_prev)
  7312         *bidi_it_prev = it->bidi_it;
  7313       set_iterator_to_next (it, false);
  7314       it->c = 0;
  7315       return true;
  7316     }
  7317 
  7318   /* Don't handle selective display in the following.  It's (a)
  7319      unnecessary because it's done by the caller, and (b) leads to an
  7320      infinite recursion because next_element_from_ellipsis indirectly
  7321      calls this function.  */
  7322   old_selective = it->selective;
  7323   it->selective = 0;
  7324 
  7325   /* Scan for a newline within MAX_NEWLINE_DISTANCE display elements
  7326      from buffer text, or till the end of the string if iterating a
  7327      string.  */
  7328   for (n = 0;
  7329        !newline_found_p && n < MAX_NEWLINE_DISTANCE;
  7330        n += !STRINGP (it->string))
  7331     {
  7332       if (!get_next_display_element (it))
  7333         return false;
  7334       newline_found_p = it->what == IT_CHARACTER && it->c == '\n';
  7335       if (newline_found_p && it->bidi_p && bidi_it_prev)
  7336         *bidi_it_prev = it->bidi_it;
  7337       set_iterator_to_next (it, false);
  7338     }
  7339 
  7340   /* If we didn't find a newline near enough, see if we can use a
  7341      short-cut.  */
  7342   if (!newline_found_p)
  7343     {
  7344       ptrdiff_t bytepos, start = IT_CHARPOS (*it);
  7345       ptrdiff_t limit = find_newline_no_quit (start, IT_BYTEPOS (*it),
  7346                                               1, &bytepos);
  7347       eassert (!STRINGP (it->string));
  7348 
  7349       /* it->stop_charpos >= limit means we already know there's no
  7350          stop position up until the newline at LIMIT, so there's no
  7351          need for any further checks.  */
  7352       bool no_strings_with_newlines = it->stop_charpos >= limit;
  7353 
  7354       if (!no_strings_with_newlines)
  7355         {
  7356           if (!(current_buffer->long_line_optimizations_p
  7357                 && it->line_wrap == TRUNCATE))
  7358             {
  7359               /* Quick-and-dirty check: if there isn't any `display'
  7360                  property in sight, and no overlays, we're done.  */
  7361               Lisp_Object pos =
  7362                 Fnext_single_property_change (make_fixnum (start),
  7363                                               Qdisplay, Qnil,
  7364                                               make_fixnum (limit));
  7365               no_strings_with_newlines =
  7366                 (NILP (pos) || XFIXNAT (pos) == limit) /* no 'display' props */
  7367                 && next_overlay_change (start) == ZV;  /* no overlays */
  7368             }
  7369           else
  7370             {
  7371               /* For buffers with very long and truncated lines we try
  7372                  harder, because it's worth our while to spend some
  7373                  time looking into the overlays and 'display' properties
  7374                  if we can then avoid iterating through all of them.  */
  7375               no_strings_with_newlines =
  7376                 !strings_with_newlines (start, limit, it->w);
  7377             }
  7378         }
  7379 
  7380       /* If there's no display or overlay strings with embedded
  7381          newlines until the position of the newline in buffer text, we
  7382          can just use that position.  */
  7383       if (no_strings_with_newlines)
  7384         {
  7385           if (!it->bidi_p || !bidi_it_prev)
  7386             {
  7387               /* The optimal case: just jump there.  */
  7388               IT_CHARPOS (*it) = limit;
  7389               IT_BYTEPOS (*it) = bytepos;
  7390             }
  7391           else
  7392             {
  7393               /* The less optimal case: need to bidi-walk there, but
  7394                  this is still cheaper that the full iteration using
  7395                  get_next_display_element and set_iterator_to_next.  */
  7396               struct bidi_it bprev;
  7397 
  7398               /* Help bidi.c avoid expensive searches for display
  7399                  properties and overlays, by telling it that there are
  7400                  none up to `limit'.  */
  7401               if (it->bidi_it.disp_pos < limit)
  7402                 {
  7403                   it->bidi_it.disp_pos = limit;
  7404                   it->bidi_it.disp_prop = 0;
  7405                 }
  7406               do {
  7407                 bprev = it->bidi_it;
  7408                 bidi_move_to_visually_next (&it->bidi_it);
  7409               } while (it->bidi_it.charpos != limit);
  7410               IT_CHARPOS (*it) = limit;
  7411               IT_BYTEPOS (*it) = it->bidi_it.bytepos;
  7412               if (bidi_it_prev)
  7413                 *bidi_it_prev = bprev;
  7414             }
  7415           *skipped_p = newline_found_p = true;
  7416         }
  7417       else
  7418         {
  7419           /* The slow case.  */
  7420           while (!newline_found_p)
  7421             {
  7422               if (!get_next_display_element (it))
  7423                 break;
  7424               newline_found_p = ITERATOR_AT_END_OF_LINE_P (it);
  7425               if (newline_found_p && it->bidi_p && bidi_it_prev)
  7426                 *bidi_it_prev = it->bidi_it;
  7427               set_iterator_to_next (it, false);
  7428             }
  7429         }
  7430     }
  7431 
  7432   it->selective = old_selective;
  7433   return newline_found_p;
  7434 }
  7435 
  7436 
  7437 /* Set IT's current position to the previous visible line start.  Skip
  7438    invisible text that is so either due to text properties or due to
  7439    selective display.  Caution: this does not change IT->current_x and
  7440    IT->hpos.  */
  7441 
  7442 static void
  7443 back_to_previous_visible_line_start (struct it *it)
  7444 {
  7445   while (IT_CHARPOS (*it) > BEGV)
  7446     {
  7447       back_to_previous_line_start (it);
  7448 
  7449       if (IT_CHARPOS (*it) <= BEGV)
  7450         break;
  7451 
  7452       /* If selective > 0, then lines indented more than its value are
  7453          invisible.  */
  7454       if (it->selective > 0
  7455           && indented_beyond_p (IT_CHARPOS (*it), IT_BYTEPOS (*it),
  7456                                 it->selective))
  7457         continue;
  7458 
  7459       /* Check the newline before point for invisibility.  */
  7460       {
  7461         Lisp_Object prop;
  7462         prop = Fget_char_property (make_fixnum (IT_CHARPOS (*it) - 1),
  7463                                    Qinvisible, it->window);
  7464         if (TEXT_PROP_MEANS_INVISIBLE (prop) != 0)
  7465           continue;
  7466       }
  7467 
  7468       if (IT_CHARPOS (*it) <= BEGV)
  7469         break;
  7470 
  7471       {
  7472         struct it it2;
  7473         void *it2data = NULL;
  7474         ptrdiff_t pos;
  7475         ptrdiff_t beg, end;
  7476         Lisp_Object val, overlay;
  7477 
  7478         SAVE_IT (it2, *it, it2data);
  7479 
  7480         /* If newline is part of a composition, continue from start of composition */
  7481         if (find_composition (IT_CHARPOS (*it), -1, &beg, &end, &val, Qnil)
  7482             && beg < IT_CHARPOS (*it))
  7483           goto replaced;
  7484 
  7485         /* If newline is replaced by a display property, find start of overlay
  7486            or interval and continue search from that point.  */
  7487         pos = --IT_CHARPOS (it2);
  7488         --IT_BYTEPOS (it2);
  7489         it2.sp = 0;
  7490         bidi_unshelve_cache (NULL, false);
  7491         it2.string_from_display_prop_p = false;
  7492         it2.from_disp_prop_p = false;
  7493         if (handle_display_prop (&it2) == HANDLED_RETURN
  7494             && !NILP (val = get_char_property_and_overlay
  7495                       (make_fixnum (pos), Qdisplay, Qnil, &overlay))
  7496             && (OVERLAYP (overlay)
  7497                 ? (beg = OVERLAY_START (overlay))
  7498                 : get_property_and_range (pos, Qdisplay, &val, &beg, &end, Qnil)))
  7499           {
  7500             RESTORE_IT (it, it, it2data);
  7501             goto replaced;
  7502           }
  7503 
  7504         /* Newline is not replaced by anything -- so we are done.  */
  7505         RESTORE_IT (it, it, it2data);
  7506         break;
  7507 
  7508       replaced:
  7509         if (beg < BEGV)
  7510           beg = BEGV;
  7511         IT_CHARPOS (*it) = beg;
  7512         IT_BYTEPOS (*it) = buf_charpos_to_bytepos (current_buffer, beg);
  7513       }
  7514     }
  7515 
  7516   it->continuation_lines_width = 0;
  7517 
  7518   eassert (IT_CHARPOS (*it) >= BEGV);
  7519   eassert (it->medium_narrowing_begv > 0 /* long-line optimizations: all bets off */
  7520            || IT_CHARPOS (*it) == BEGV
  7521            || FETCH_BYTE (IT_BYTEPOS (*it) - 1) == '\n');
  7522   CHECK_IT (it);
  7523 }
  7524 
  7525 
  7526 /* Reseat iterator IT at the previous visible line start.  Skip
  7527    invisible text that is so either due to text properties or due to
  7528    selective display.  At the end, update IT's overlay information,
  7529    face information etc.  */
  7530 
  7531 void
  7532 reseat_at_previous_visible_line_start (struct it *it)
  7533 {
  7534   back_to_previous_visible_line_start (it);
  7535   reseat (it, it->current.pos, true);
  7536   CHECK_IT (it);
  7537 }
  7538 
  7539 
  7540 /* Reseat iterator IT on the next visible line start in the current
  7541    buffer.  ON_NEWLINE_P means position IT on the newline
  7542    preceding the line start.  Skip over invisible text that is so
  7543    because of selective display.  Compute faces, overlays etc at the
  7544    new position.  Note that this function does not skip over text that
  7545    is invisible because of text properties.  */
  7546 
  7547 static void
  7548 reseat_at_next_visible_line_start (struct it *it, bool on_newline_p)
  7549 {
  7550   bool skipped_p = false;
  7551   struct bidi_it bidi_it_prev;
  7552   bool newline_found_p
  7553     = forward_to_next_line_start (it, &skipped_p,
  7554                                   on_newline_p ? &bidi_it_prev : NULL);
  7555 
  7556   /* Skip over lines that are invisible because they are indented
  7557      more than the value of IT->selective.  */
  7558   if (it->selective > 0)
  7559     while (IT_CHARPOS (*it) < ZV
  7560            && indented_beyond_p (IT_CHARPOS (*it), IT_BYTEPOS (*it),
  7561                                  it->selective))
  7562       {
  7563         eassert (IT_BYTEPOS (*it) == BEGV
  7564                  || FETCH_BYTE (IT_BYTEPOS (*it) - 1) == '\n');
  7565         newline_found_p =
  7566           forward_to_next_line_start (it, &skipped_p,
  7567                                       on_newline_p ? &bidi_it_prev : NULL);
  7568       }
  7569 
  7570   /* Position on the newline if that's what's requested.  */
  7571   if (on_newline_p && newline_found_p)
  7572     {
  7573       if (STRINGP (it->string))
  7574         {
  7575           if (IT_STRING_CHARPOS (*it) > 0)
  7576             {
  7577               if (!it->bidi_p)
  7578                 {
  7579                   --IT_STRING_CHARPOS (*it);
  7580                   --IT_STRING_BYTEPOS (*it);
  7581                 }
  7582               else
  7583                 {
  7584                   /* We need to restore the bidi iterator to the state
  7585                      it had on the newline, and resync the IT's
  7586                      position with that.  */
  7587                   it->bidi_it = bidi_it_prev;
  7588                   IT_STRING_CHARPOS (*it) = it->bidi_it.charpos;
  7589                   IT_STRING_BYTEPOS (*it) = it->bidi_it.bytepos;
  7590                 }
  7591             }
  7592         }
  7593       else if (IT_CHARPOS (*it) > BEGV)
  7594         {
  7595           if (!it->bidi_p)
  7596             {
  7597               --IT_CHARPOS (*it);
  7598               --IT_BYTEPOS (*it);
  7599             }
  7600           else
  7601             {
  7602               /* We need to restore the bidi iterator to the state it
  7603                  had on the newline and resync IT with that.  */
  7604               it->bidi_it = bidi_it_prev;
  7605               IT_CHARPOS (*it) = it->bidi_it.charpos;
  7606               IT_BYTEPOS (*it) = it->bidi_it.bytepos;
  7607             }
  7608           reseat (it, it->current.pos, false);
  7609         }
  7610     }
  7611   else if (skipped_p)
  7612     reseat (it, it->current.pos, false);
  7613 
  7614   CHECK_IT (it);
  7615 }
  7616 
  7617 
  7618 
  7619 /***********************************************************************
  7620                    Changing an iterator's position
  7621 ***********************************************************************/
  7622 
  7623 /* Change IT's current position to POS in current_buffer.
  7624    If FORCE_P, always check for text properties at the new position.
  7625    Otherwise, text properties are only looked up if POS >=
  7626    IT->check_charpos of a property.  */
  7627 
  7628 static void
  7629 reseat (struct it *it, struct text_pos pos, bool force_p)
  7630 {
  7631   ptrdiff_t original_pos = IT_CHARPOS (*it);
  7632 
  7633   reseat_1 (it, pos, false);
  7634 
  7635   if (current_buffer->long_line_optimizations_p)
  7636     {
  7637       if (!it->medium_narrowing_begv)
  7638         {
  7639           it->medium_narrowing_begv
  7640             = get_medium_narrowing_begv (it->w, window_point (it->w));
  7641           it->medium_narrowing_zv
  7642             = get_medium_narrowing_zv (it->w, window_point (it->w));
  7643           it->large_narrowing_begv
  7644             = get_large_narrowing_begv (window_point (it->w));
  7645           it->large_narrowing_zv
  7646             = get_large_narrowing_zv (window_point (it->w));
  7647         }
  7648       else if ((pos.charpos < it->medium_narrowing_begv
  7649                 || pos.charpos > it->medium_narrowing_zv)
  7650                 && (!redisplaying_p || it->line_wrap == TRUNCATE))
  7651         {
  7652           it->medium_narrowing_begv
  7653             = get_medium_narrowing_begv (it->w, pos.charpos);
  7654           it->medium_narrowing_zv
  7655             = get_medium_narrowing_zv (it->w, pos.charpos);
  7656           it->large_narrowing_begv
  7657             = get_large_narrowing_begv (window_point (it->w));
  7658           it->large_narrowing_zv
  7659             = get_large_narrowing_zv (window_point (it->w));
  7660         }
  7661     }
  7662 
  7663   /* Determine where to check text properties.  Avoid doing it
  7664      where possible because text property lookup is very expensive.  */
  7665   if (force_p
  7666       || CHARPOS (pos) > it->stop_charpos
  7667       || CHARPOS (pos) < original_pos)
  7668     {
  7669       if (it->bidi_p)
  7670         {
  7671           /* For bidi iteration, we need to prime prev_stop and
  7672              base_level_stop with our best estimations.  */
  7673           /* Implementation note: Of course, POS is not necessarily a
  7674              stop position, so assigning prev_pos to it is a lie; we
  7675              should have called compute_stop_backwards.  However, if
  7676              the current buffer does not include any R2L characters,
  7677              that call would be a waste of cycles, because the
  7678              iterator will never move back, and thus never cross this
  7679              "fake" stop position.  So we delay that backward search
  7680              until the time we really need it, in next_element_from_buffer.  */
  7681           if (CHARPOS (pos) != it->prev_stop)
  7682             it->prev_stop = CHARPOS (pos);
  7683           if (CHARPOS (pos) < it->base_level_stop)
  7684             it->base_level_stop = 0; /* meaning it's unknown */
  7685           handle_stop (it);
  7686         }
  7687       else
  7688         {
  7689           handle_stop (it);
  7690           it->prev_stop = it->base_level_stop = 0;
  7691         }
  7692 
  7693     }
  7694 
  7695   CHECK_IT (it);
  7696 }
  7697 
  7698 
  7699 /* Change IT's buffer position to POS.  SET_STOP_P means set
  7700    IT->stop_pos to POS, also.  */
  7701 
  7702 static void
  7703 reseat_1 (struct it *it, struct text_pos pos, bool set_stop_p)
  7704 {
  7705   /* Don't call this function when scanning a C string.  */
  7706   eassert (it->s == NULL);
  7707 
  7708   /* POS must be a reasonable value.  */
  7709   eassert (CHARPOS (pos) >= BEGV && CHARPOS (pos) <= ZV);
  7710 
  7711   it->current.pos = it->position = pos;
  7712   it->end_charpos = ZV;
  7713   it->dpvec = NULL;
  7714   it->current.dpvec_index = -1;
  7715   it->current.overlay_string_index = -1;
  7716   IT_STRING_CHARPOS (*it) = -1;
  7717   IT_STRING_BYTEPOS (*it) = -1;
  7718   it->string = Qnil;
  7719   it->method = GET_FROM_BUFFER;
  7720   it->object = it->w->contents;
  7721   it->area = TEXT_AREA;
  7722   it->multibyte_p = !NILP (BVAR (current_buffer, enable_multibyte_characters));
  7723   it->sp = 0;
  7724   it->string_from_display_prop_p = false;
  7725   it->string_from_prefix_prop_p = false;
  7726 
  7727   it->from_disp_prop_p = false;
  7728   it->face_before_selective_p = false;
  7729   if (it->bidi_p)
  7730     {
  7731       bidi_init_it (IT_CHARPOS (*it), IT_BYTEPOS (*it), FRAME_WINDOW_P (it->f),
  7732                     &it->bidi_it);
  7733       bidi_unshelve_cache (NULL, false);
  7734       it->bidi_it.paragraph_dir = NEUTRAL_DIR;
  7735       it->bidi_it.string.s = NULL;
  7736       it->bidi_it.string.lstring = Qnil;
  7737       it->bidi_it.string.bufpos = 0;
  7738       it->bidi_it.string.from_disp_str = false;
  7739       it->bidi_it.string.unibyte = false;
  7740       it->bidi_it.w = it->w;
  7741     }
  7742 
  7743   if (set_stop_p)
  7744     {
  7745       it->stop_charpos = CHARPOS (pos);
  7746       it->base_level_stop = CHARPOS (pos);
  7747     }
  7748   /* This make the information stored in it->cmp_it invalidate.  */
  7749   it->cmp_it.id = -1;
  7750   it->min_width_property = Qnil;
  7751 }
  7752 
  7753 
  7754 /* Set up IT for displaying a string, starting at CHARPOS in window W.
  7755    If S is non-null, it is a C string to iterate over.  Otherwise,
  7756    STRING gives a Lisp string to iterate over.
  7757 
  7758    If PRECISION > 0, don't return more then PRECISION number of
  7759    characters from the string.
  7760 
  7761    If FIELD_WIDTH > 0, return padding spaces until FIELD_WIDTH
  7762    characters have been returned.  FIELD_WIDTH < 0 means an infinite
  7763    field width.
  7764 
  7765    MULTIBYTE = 0 means disable processing of multibyte characters,
  7766    MULTIBYTE > 0 means enable it,
  7767    MULTIBYTE < 0 means use IT->multibyte_p.
  7768 
  7769    IT must be initialized via a prior call to init_iterator before
  7770    calling this function.  */
  7771 
  7772 static void
  7773 reseat_to_string (struct it *it, const char *s, Lisp_Object string,
  7774                   ptrdiff_t charpos, ptrdiff_t precision, int field_width,
  7775                   int multibyte)
  7776 {
  7777   /* No text property checks performed by default, but see below.  */
  7778   it->stop_charpos = -1;
  7779 
  7780   /* Set iterator position and end position.  */
  7781   memset (&it->current, 0, sizeof it->current);
  7782   it->current.overlay_string_index = -1;
  7783   it->current.dpvec_index = -1;
  7784   eassert (charpos >= 0);
  7785 
  7786   /* If STRING is specified, use its multibyteness, otherwise use the
  7787      setting of MULTIBYTE, if specified.  */
  7788   if (multibyte >= 0)
  7789     it->multibyte_p = multibyte > 0;
  7790 
  7791   /* Bidirectional reordering of strings is controlled by the default
  7792      value of bidi-display-reordering.  Don't try to reorder while
  7793      loading loadup.el, as the necessary character property tables are
  7794      not yet available.  */
  7795   it->bidi_p =
  7796     !redisplay__inhibit_bidi
  7797     && !NILP (BVAR (&buffer_defaults, bidi_display_reordering));
  7798 
  7799   if (s == NULL)
  7800     {
  7801       eassert (STRINGP (string));
  7802       it->string = string;
  7803       it->s = NULL;
  7804       it->end_charpos = it->string_nchars = SCHARS (string);
  7805       it->method = GET_FROM_STRING;
  7806       it->current.string_pos = string_pos (charpos, string);
  7807 
  7808       if (it->bidi_p)
  7809         {
  7810           it->bidi_it.string.lstring = string;
  7811           it->bidi_it.string.s = NULL;
  7812           it->bidi_it.string.schars = it->end_charpos;
  7813           it->bidi_it.string.bufpos = 0;
  7814           it->bidi_it.string.from_disp_str = false;
  7815           it->bidi_it.string.unibyte = !it->multibyte_p;
  7816           it->bidi_it.w = it->w;
  7817           bidi_init_it (charpos, IT_STRING_BYTEPOS (*it),
  7818                         FRAME_WINDOW_P (it->f), &it->bidi_it);
  7819         }
  7820     }
  7821   else
  7822     {
  7823       it->s = (const unsigned char *) s;
  7824       it->string = Qnil;
  7825 
  7826       /* Note that we use IT->current.pos, not it->current.string_pos,
  7827          for displaying C strings.  */
  7828       IT_STRING_CHARPOS (*it) = IT_STRING_BYTEPOS (*it) = -1;
  7829       if (it->multibyte_p)
  7830         {
  7831           it->current.pos = c_string_pos (charpos, s, true);
  7832           it->end_charpos = it->string_nchars = number_of_chars (s, true);
  7833         }
  7834       else
  7835         {
  7836           IT_CHARPOS (*it) = IT_BYTEPOS (*it) = charpos;
  7837           it->end_charpos = it->string_nchars = strlen (s);
  7838         }
  7839 
  7840       if (it->bidi_p)
  7841         {
  7842           it->bidi_it.string.lstring = Qnil;
  7843           it->bidi_it.string.s = (const unsigned char *) s;
  7844           it->bidi_it.string.schars = it->end_charpos;
  7845           it->bidi_it.string.bufpos = 0;
  7846           it->bidi_it.string.from_disp_str = false;
  7847           it->bidi_it.string.unibyte = !it->multibyte_p;
  7848           it->bidi_it.w = it->w;
  7849           bidi_init_it (charpos, IT_BYTEPOS (*it), FRAME_WINDOW_P (it->f),
  7850                         &it->bidi_it);
  7851         }
  7852       it->method = GET_FROM_C_STRING;
  7853     }
  7854 
  7855   /* PRECISION > 0 means don't return more than PRECISION characters
  7856      from the string.  */
  7857   if (precision > 0 && it->end_charpos - charpos > precision)
  7858     {
  7859       it->end_charpos = it->string_nchars = charpos + precision;
  7860       if (it->bidi_p)
  7861         it->bidi_it.string.schars = it->end_charpos;
  7862     }
  7863 
  7864   /* FIELD_WIDTH > 0 means pad with spaces until FIELD_WIDTH
  7865      characters have been returned.  FIELD_WIDTH == 0 means don't pad,
  7866      FIELD_WIDTH < 0 means infinite field width.  This is useful for
  7867      padding with `-' at the end of a mode line.  */
  7868   if (field_width < 0)
  7869     field_width = DISP_INFINITY;
  7870   /* Implementation note: We deliberately don't enlarge
  7871      it->bidi_it.string.schars here to fit it->end_charpos, because
  7872      the bidi iterator cannot produce characters out of thin air.  */
  7873   if (field_width > it->end_charpos - charpos)
  7874     it->end_charpos = charpos + field_width;
  7875 
  7876   /* Use the standard display table for displaying strings.  */
  7877   if (DISP_TABLE_P (Vstandard_display_table))
  7878     it->dp = XCHAR_TABLE (Vstandard_display_table);
  7879 
  7880   it->stop_charpos = charpos;
  7881   it->prev_stop = charpos;
  7882   it->base_level_stop = 0;
  7883   if (it->bidi_p)
  7884     {
  7885       it->bidi_it.first_elt = true;
  7886       it->bidi_it.paragraph_dir = NEUTRAL_DIR;
  7887       it->bidi_it.disp_pos = -1;
  7888     }
  7889   if (s == NULL && it->multibyte_p)
  7890     {
  7891       ptrdiff_t endpos = SCHARS (it->string);
  7892       if (endpos > it->end_charpos)
  7893         endpos = it->end_charpos;
  7894       composition_compute_stop_pos (&it->cmp_it, charpos, -1, endpos,
  7895                                     it->string, true);
  7896     }
  7897   CHECK_IT (it);
  7898 }
  7899 
  7900 
  7901 
  7902 /***********************************************************************
  7903                               Iteration
  7904 ***********************************************************************/
  7905 
  7906 /* Map enum it_method value to corresponding next_element_from_* function.  */
  7907 
  7908 typedef bool (*next_element_function) (struct it *);
  7909 
  7910 static next_element_function const get_next_element[NUM_IT_METHODS] =
  7911 {
  7912   next_element_from_buffer,
  7913   next_element_from_display_vector,
  7914   next_element_from_string,
  7915   next_element_from_c_string,
  7916   next_element_from_image,
  7917   next_element_from_stretch,
  7918   next_element_from_xwidget,
  7919 };
  7920 
  7921 #define GET_NEXT_DISPLAY_ELEMENT(it) (*get_next_element[(it)->method]) (it)
  7922 
  7923 
  7924 /* Return true iff a character at CHARPOS (and BYTEPOS) is composed
  7925    (possibly with the following characters).
  7926 
  7927   Note: we pass -1 as the "resolved bidi level" when the iterator
  7928   doesn't have the bidi_p flag set, because in that case we really
  7929   don't know what is the directionality of the text, so we leave it to
  7930   the shaping engine to figure that out.  */
  7931 
  7932 #define CHAR_COMPOSED_P(IT,CHARPOS,BYTEPOS,END_CHARPOS)                 \
  7933   ((IT)->cmp_it.id >= 0                                                 \
  7934    || ((IT)->cmp_it.stop_pos == (CHARPOS)                               \
  7935        && composition_reseat_it (&(IT)->cmp_it, CHARPOS, BYTEPOS,       \
  7936                                  END_CHARPOS, (IT)->w,                  \
  7937                                  (IT)->bidi_p                           \
  7938                                  ? (IT)->bidi_it.resolved_level         \
  7939                                  : -1,                                  \
  7940                                  FACE_FROM_ID_OR_NULL ((IT)->f,         \
  7941                                                        (IT)->face_id),  \
  7942                                  (IT)->string)))
  7943 
  7944 
  7945 /* Lookup the char-table Vglyphless_char_display for character C (-1
  7946    if we want information for no-font case), and return the display
  7947    method symbol.  By side-effect, update it->what and
  7948    it->glyphless_method.  This function is called from
  7949    get_next_display_element for each character element, and from
  7950    gui_produce_glyphs when no suitable font was found.  */
  7951 
  7952 Lisp_Object
  7953 lookup_glyphless_char_display (int c, struct it *it)
  7954 {
  7955   Lisp_Object glyphless_method = Qnil;
  7956 
  7957   if (CHAR_TABLE_P (Vglyphless_char_display)
  7958       && CHAR_TABLE_EXTRA_SLOTS (XCHAR_TABLE (Vglyphless_char_display)) >= 1)
  7959     {
  7960       if (c >= 0)
  7961         glyphless_method = CHAR_TABLE_REF (Vglyphless_char_display, c);
  7962       else
  7963         glyphless_method = XCHAR_TABLE (Vglyphless_char_display)->extras[0];
  7964 
  7965       if (CONSP (glyphless_method))
  7966         glyphless_method = FRAME_WINDOW_P (it->f)
  7967           ? XCAR (glyphless_method)
  7968           : XCDR (glyphless_method);
  7969     }
  7970 
  7971  retry:
  7972   if (NILP (glyphless_method))
  7973     {
  7974       if (c >= 0)
  7975         /* The default is to display the character by a proper font.  */
  7976         return Qnil;
  7977       /* The default for the no-font case is to display an empty box.  */
  7978       glyphless_method = Qempty_box;
  7979     }
  7980   if (EQ (glyphless_method, Qzero_width))
  7981     {
  7982       if (c >= 0)
  7983         return glyphless_method;
  7984       /* This method can't be used for the no-font case.  */
  7985       glyphless_method = Qempty_box;
  7986     }
  7987   if (EQ (glyphless_method, Qthin_space))
  7988     it->glyphless_method = GLYPHLESS_DISPLAY_THIN_SPACE;
  7989   else if (EQ (glyphless_method, Qempty_box))
  7990     it->glyphless_method = GLYPHLESS_DISPLAY_EMPTY_BOX;
  7991   else if (EQ (glyphless_method, Qhex_code))
  7992     it->glyphless_method = GLYPHLESS_DISPLAY_HEX_CODE;
  7993   else if (STRINGP (glyphless_method))
  7994     it->glyphless_method = GLYPHLESS_DISPLAY_ACRONYM;
  7995   else
  7996     {
  7997       /* Invalid value.  We use the default method.  */
  7998       glyphless_method = Qnil;
  7999       goto retry;
  8000     }
  8001   it->what = IT_GLYPHLESS;
  8002   return glyphless_method;
  8003 }
  8004 
  8005 /* Merge escape glyph face and cache the result.  */
  8006 
  8007 static struct frame *last_escape_glyph_frame = NULL;
  8008 static int last_escape_glyph_face_id = (1 << FACE_ID_BITS);
  8009 static int last_escape_glyph_merged_face_id = 0;
  8010 
  8011 static int
  8012 merge_escape_glyph_face (struct it *it)
  8013 {
  8014   int face_id;
  8015 
  8016   if (it->f == last_escape_glyph_frame
  8017       && it->face_id == last_escape_glyph_face_id)
  8018     face_id = last_escape_glyph_merged_face_id;
  8019   else
  8020     {
  8021       /* Merge the `escape-glyph' face into the current face.  */
  8022       face_id = merge_faces (it->w, Qescape_glyph, 0, it->face_id);
  8023       last_escape_glyph_frame = it->f;
  8024       last_escape_glyph_face_id = it->face_id;
  8025       last_escape_glyph_merged_face_id = face_id;
  8026     }
  8027   return face_id;
  8028 }
  8029 
  8030 /* Likewise for glyphless glyph face.  */
  8031 
  8032 static struct frame *last_glyphless_glyph_frame = NULL;
  8033 static int last_glyphless_glyph_face_id = (1 << FACE_ID_BITS);
  8034 static int last_glyphless_glyph_merged_face_id = 0;
  8035 
  8036 int
  8037 merge_glyphless_glyph_face (struct it *it)
  8038 {
  8039   int face_id;
  8040 
  8041   if (it->f == last_glyphless_glyph_frame
  8042       && it->face_id == last_glyphless_glyph_face_id)
  8043     face_id = last_glyphless_glyph_merged_face_id;
  8044   else
  8045     {
  8046       /* Merge the `glyphless-char' face into the current face.  */
  8047       face_id = merge_faces (it->w, Qglyphless_char, 0, it->face_id);
  8048       last_glyphless_glyph_frame = it->f;
  8049       last_glyphless_glyph_face_id = it->face_id;
  8050       last_glyphless_glyph_merged_face_id = face_id;
  8051     }
  8052   return face_id;
  8053 }
  8054 
  8055 /* Forget the `escape-glyph' and `glyphless-char' faces.  This should
  8056    be called before redisplaying windows, and when the frame's face
  8057    cache is freed.  */
  8058 void
  8059 forget_escape_and_glyphless_faces (void)
  8060 {
  8061   last_escape_glyph_frame = NULL;
  8062   last_escape_glyph_face_id = (1 << FACE_ID_BITS);
  8063   last_glyphless_glyph_frame = NULL;
  8064   last_glyphless_glyph_face_id = (1 << FACE_ID_BITS);
  8065 }
  8066 
  8067 /* Load IT's display element fields with information about the next
  8068    display element from the current position of IT.  Value is false if
  8069    end of buffer (or C string) is reached.  */
  8070 
  8071 static bool
  8072 get_next_display_element (struct it *it)
  8073 {
  8074   /* True means that we found a display element.  False means that
  8075      we hit the end of what we iterate over.  Performance note: the
  8076      function pointer `method' used here turns out to be faster than
  8077      using a sequence of if-statements.  */
  8078   bool success_p;
  8079 
  8080  get_next:
  8081   success_p = GET_NEXT_DISPLAY_ELEMENT (it);
  8082 
  8083   if (it->what == IT_CHARACTER)
  8084     {
  8085       /* UAX#9, L4: "A character is depicted by a mirrored glyph if
  8086          and only if (a) the resolved directionality of that character
  8087          is R..."  */
  8088       /* FIXME: Do we need an exception for characters from display
  8089          tables?  */
  8090       if (it->bidi_p && it->bidi_it.type == STRONG_R
  8091           && !inhibit_bidi_mirroring)
  8092         it->c = bidi_mirror_char (it->c);
  8093       /* Map via display table or translate control characters.
  8094          IT->c, IT->len etc. have been set to the next character by
  8095          the function call above.  If we have a display table, and it
  8096          contains an entry for IT->c, translate it.  Don't do this if
  8097          IT->c itself comes from a display table, otherwise we could
  8098          end up in an infinite recursion.  (An alternative could be to
  8099          count the recursion depth of this function and signal an
  8100          error when a certain maximum depth is reached.)  Is it worth
  8101          it?  */
  8102       if (success_p && it->dpvec == NULL)
  8103         {
  8104           Lisp_Object dv;
  8105           struct charset *unibyte = CHARSET_FROM_ID (charset_unibyte);
  8106           bool nonascii_space_p = false;
  8107           bool nonascii_hyphen_p = false;
  8108           int c = it->c;        /* This is the character to display.  */
  8109 
  8110           if (! it->multibyte_p && ! ASCII_CHAR_P (c))
  8111             {
  8112               eassert (SINGLE_BYTE_CHAR_P (c));
  8113               if (unibyte_display_via_language_environment)
  8114                 {
  8115                   c = DECODE_CHAR (unibyte, c);
  8116                   if (c < 0)
  8117                     c = BYTE8_TO_CHAR (it->c);
  8118                 }
  8119               else
  8120                 c = BYTE8_TO_CHAR (it->c);
  8121             }
  8122 
  8123           if (it->dp
  8124               && (dv = DISP_CHAR_VECTOR (it->dp, c),
  8125                   VECTORP (dv)))
  8126             {
  8127               struct Lisp_Vector *v = XVECTOR (dv);
  8128 
  8129               /* Return the first character from the display table
  8130                  entry, if not empty.  If empty, don't display the
  8131                  current character.  */
  8132               if (v->header.size)
  8133                 {
  8134                   it->dpvec_char_len = it->len;
  8135                   it->dpvec = v->contents;
  8136                   it->dpend = v->contents + v->header.size;
  8137                   it->current.dpvec_index = 0;
  8138                   it->dpvec_face_id = -1;
  8139                   it->saved_face_id = it->face_id;
  8140                   it->method = GET_FROM_DISPLAY_VECTOR;
  8141                   it->ellipsis_p = false;
  8142                 }
  8143               else
  8144                 {
  8145                   set_iterator_to_next (it, false);
  8146                 }
  8147               goto get_next;
  8148             }
  8149 
  8150           if (! NILP (lookup_glyphless_char_display (c, it)))
  8151             {
  8152               if (it->what == IT_GLYPHLESS)
  8153                 goto done;
  8154               /* Don't display this character.  */
  8155               set_iterator_to_next (it, false);
  8156               goto get_next;
  8157             }
  8158 
  8159           /* If `nobreak-char-display' is non-nil, we display
  8160              non-ASCII spaces and hyphens specially.  */
  8161           if (! ASCII_CHAR_P (c) && ! NILP (Vnobreak_char_display))
  8162             {
  8163               if (blankp (c))
  8164                 nonascii_space_p = true;
  8165               else if (c == SOFT_HYPHEN || c == HYPHEN
  8166                        || c == NON_BREAKING_HYPHEN)
  8167                 nonascii_hyphen_p = true;
  8168             }
  8169 
  8170           /* Translate control characters into `\003' or `^C' form.
  8171              Control characters coming from a display table entry are
  8172              currently not translated because we use IT->dpvec to hold
  8173              the translation.  This could easily be changed but I
  8174              don't believe that it is worth doing.
  8175 
  8176              The characters handled by `nobreak-char-display' must be
  8177              translated too.
  8178 
  8179              Non-printable characters and raw-byte characters are also
  8180              translated to octal or hexadecimal form.  */
  8181           if (((c < ' ' || c == 127) /* ASCII control chars.  */
  8182                ? (it->area != TEXT_AREA
  8183                   /* In mode line, treat \n, \t like other crl chars.  */
  8184                   || (c != '\t'
  8185                       && it->glyph_row
  8186                       && (it->glyph_row->mode_line_p || it->avoid_cursor_p))
  8187                   || (c != '\n' && c != '\t'))
  8188                : (nonascii_space_p
  8189                   || nonascii_hyphen_p
  8190                   || CHAR_BYTE8_P (c)
  8191                   || ! CHAR_PRINTABLE_P (c))))
  8192             {
  8193               /* C is a control character, non-ASCII space/hyphen,
  8194                  raw-byte, or a non-printable character which must be
  8195                  displayed either as '\003' or as `^C' where the '\\'
  8196                  and '^' can be defined in the display table.  Fill
  8197                  IT->ctl_chars with glyphs for what we have to
  8198                  display.  Then, set IT->dpvec to these glyphs.  */
  8199               Lisp_Object gc;
  8200               int ctl_len;
  8201               int face_id;
  8202               int lface_id = 0;
  8203               int escape_glyph;
  8204 
  8205               /* Handle control characters with ^.  */
  8206 
  8207               if (ASCII_CHAR_P (c) && it->ctl_arrow_p)
  8208                 {
  8209                   int g;
  8210 
  8211                   g = '^';           /* default glyph for Control */
  8212                   /* Set IT->ctl_chars[0] to the glyph for `^'.  */
  8213                   if (it->dp
  8214                       && (gc = DISP_CTRL_GLYPH (it->dp), GLYPH_CODE_P (gc)))
  8215                     {
  8216                       g = GLYPH_CODE_CHAR (gc);
  8217                       lface_id = GLYPH_CODE_FACE (gc);
  8218                     }
  8219 
  8220                   face_id = (lface_id
  8221                              ? merge_faces (it->w, Qt, lface_id, it->face_id)
  8222                              : merge_escape_glyph_face (it));
  8223 
  8224                   XSETINT (it->ctl_chars[0], g);
  8225                   XSETINT (it->ctl_chars[1], c ^ 0100);
  8226                   ctl_len = 2;
  8227                   goto display_control;
  8228                 }
  8229 
  8230               /* Handle non-ascii space in the mode where it only gets
  8231                  highlighting.  */
  8232 
  8233               if (nonascii_space_p && EQ (Vnobreak_char_display, Qt))
  8234                 {
  8235                   /* Merge `nobreak-space' into the current face.  */
  8236                   face_id = merge_faces (it->w, Qnobreak_space, 0,
  8237                                          it->face_id);
  8238                   XSETINT (it->ctl_chars[0],
  8239                            nobreak_char_ascii_display ? ' ' : it->c);
  8240                   ctl_len = 1;
  8241                   goto display_control;
  8242                 }
  8243 
  8244               /* Handle non-ascii hyphens in the mode where it only
  8245                  gets highlighting.  */
  8246 
  8247               if (nonascii_hyphen_p && EQ (Vnobreak_char_display, Qt))
  8248                 {
  8249                   /* Merge `nobreak-space' into the current face.  */
  8250                   face_id = merge_faces (it->w, Qnobreak_hyphen, 0,
  8251                                          it->face_id);
  8252                   XSETINT (it->ctl_chars[0],
  8253                            nobreak_char_ascii_display ? '-' : it->c);
  8254                   ctl_len = 1;
  8255                   goto display_control;
  8256                 }
  8257 
  8258               /* Handle sequences that start with the "escape glyph".  */
  8259 
  8260               /* the default escape glyph is \.  */
  8261               escape_glyph = '\\';
  8262 
  8263               if (it->dp
  8264                   && (gc = DISP_ESCAPE_GLYPH (it->dp), GLYPH_CODE_P (gc)))
  8265                 {
  8266                   escape_glyph = GLYPH_CODE_CHAR (gc);
  8267                   lface_id = GLYPH_CODE_FACE (gc);
  8268                 }
  8269 
  8270               face_id = (lface_id
  8271                          ? merge_faces (it->w, Qt, lface_id, it->face_id)
  8272                          : merge_escape_glyph_face (it));
  8273 
  8274               /* Draw non-ASCII space/hyphen with escape glyph: */
  8275 
  8276               if (nonascii_space_p || nonascii_hyphen_p)
  8277                 {
  8278                   XSETINT (it->ctl_chars[0], escape_glyph);
  8279                   XSETINT (it->ctl_chars[1], nonascii_space_p ? ' ' : '-');
  8280                   ctl_len = 2;
  8281                   goto display_control;
  8282                 }
  8283 
  8284               {
  8285                 char str[10];
  8286                 int len, i;
  8287 
  8288                 if (CHAR_BYTE8_P (c))
  8289                   /* Display \200 or \x80 instead of \17777600.  */
  8290                   c = CHAR_TO_BYTE8 (c);
  8291                 const char *format_string = display_raw_bytes_as_hex
  8292                                             ? "x%02x"
  8293                                             : "%03o";
  8294                 len = sprintf (str, format_string, c + 0u);
  8295 
  8296                 XSETINT (it->ctl_chars[0], escape_glyph);
  8297                 for (i = 0; i < len; i++)
  8298                   XSETINT (it->ctl_chars[i + 1], str[i]);
  8299                 ctl_len = len + 1;
  8300               }
  8301 
  8302             display_control:
  8303               /* Set up IT->dpvec and return first character from it.  */
  8304               it->dpvec_char_len = it->len;
  8305               it->dpvec = it->ctl_chars;
  8306               it->dpend = it->dpvec + ctl_len;
  8307               it->current.dpvec_index = 0;
  8308               it->dpvec_face_id = face_id;
  8309               it->saved_face_id = it->face_id;
  8310               it->method = GET_FROM_DISPLAY_VECTOR;
  8311               it->ellipsis_p = false;
  8312               goto get_next;
  8313             }
  8314           it->char_to_display = c;
  8315         }
  8316       else if (success_p)
  8317         {
  8318           it->char_to_display = it->c;
  8319         }
  8320     }
  8321 
  8322 #ifdef HAVE_WINDOW_SYSTEM
  8323   /* Adjust face id for a multibyte character.  There are no multibyte
  8324      character in unibyte text.  */
  8325   if ((it->what == IT_CHARACTER || it->what == IT_COMPOSITION)
  8326       && it->multibyte_p
  8327       && success_p
  8328       && FRAME_WINDOW_P (it->f))
  8329     {
  8330       struct face *face = FACE_FROM_ID (it->f, it->face_id);
  8331 
  8332       if (it->what == IT_COMPOSITION && it->cmp_it.ch >= 0)
  8333         {
  8334           /* Automatic composition with glyph-string.   */
  8335           Lisp_Object gstring = composition_gstring_from_id (it->cmp_it.id);
  8336 
  8337           it->face_id = face_for_font (it->f, LGSTRING_FONT (gstring), face);
  8338         }
  8339       else
  8340         {
  8341           ptrdiff_t pos = (it->s ? -1
  8342                      : STRINGP (it->string) ? IT_STRING_CHARPOS (*it)
  8343                      : IT_CHARPOS (*it));
  8344           int c;
  8345 
  8346           if (it->what == IT_CHARACTER)
  8347             c = it->char_to_display;
  8348           else
  8349             {
  8350               struct composition *cmp = composition_table[it->cmp_it.id];
  8351               int i;
  8352 
  8353               c = ' ';
  8354               for (i = 0; i < cmp->glyph_len; i++)
  8355                 /* TAB in a composition means display glyphs with
  8356                    padding space on the left or right.  */
  8357                 if ((c = COMPOSITION_GLYPH (cmp, i)) != '\t')
  8358                   break;
  8359             }
  8360           it->face_id = FACE_FOR_CHAR (it->f, face, c, pos, it->string);
  8361         }
  8362     }
  8363 #endif  /* HAVE_WINDOW_SYSTEM */
  8364 
  8365  done:
  8366   /* Is this character the last one of a run of characters with
  8367      box?  If yes, set IT->end_of_box_run_p to true.  */
  8368   if (it->face_box_p
  8369       && it->s == NULL)
  8370     {
  8371       if (it->method == GET_FROM_STRING && it->sp)
  8372         {
  8373           int face_id = underlying_face_id (it);
  8374           struct face *face = FACE_FROM_ID_OR_NULL (it->f, face_id);
  8375 
  8376           if (face)
  8377             {
  8378               if (face->box == FACE_NO_BOX)
  8379                 {
  8380                   /* If the box comes from face properties in a
  8381                      display string, check faces in that string.  */
  8382                   int string_face_id = face_after_it_pos (it);
  8383                   if (FACE_FROM_ID (it->f, string_face_id)->box == FACE_NO_BOX)
  8384                     it->end_of_box_run_p = true;
  8385                 }
  8386               /* Otherwise, the box comes from the underlying face.
  8387                  If this is the last string character displayed, check
  8388                  the next buffer location.  */
  8389               else if (((IT_STRING_CHARPOS (*it) >= SCHARS (it->string) - 1)
  8390                         /* For a composition, see if the string ends
  8391                            at the last character included in the
  8392                            composition.  */
  8393                         || (it->what == IT_COMPOSITION
  8394                             && (IT_STRING_CHARPOS (*it) + it->cmp_it.nchars
  8395                                 >= SCHARS (it->string))))
  8396                        /* n_overlay_strings is unreliable unless
  8397                           overlay_string_index is non-negative.  */
  8398                        && ((it->current.overlay_string_index >= 0
  8399                             && (it->current.overlay_string_index
  8400                                 == it->n_overlay_strings - 1))
  8401                            /* A string from display property.  */
  8402                            || it->from_disp_prop_p))
  8403                 {
  8404                   ptrdiff_t ignore;
  8405                   int next_face_id;
  8406                   bool text_from_string = false;
  8407                   /* Normally, the next buffer location is stored in
  8408                      IT->current.pos...  */
  8409                   struct text_pos pos = it->current.pos;
  8410 
  8411                   /* ...but for a string from a display property, the
  8412                      next buffer position is stored in the 'position'
  8413                      member of the iteration stack slot below the
  8414                      current one, see handle_single_display_spec.  By
  8415                      contrast, it->current.pos was not yet updated to
  8416                      point to that buffer position; that will happen
  8417                      in pop_it, after we finish displaying the current
  8418                      string.  Note that we already checked above that
  8419                      it->sp is positive, so subtracting one from it is
  8420                      safe.  */
  8421                   if (it->from_disp_prop_p)
  8422                     {
  8423                       int stackp = it->sp - 1;
  8424 
  8425                       /* Find the stack level with data from buffer.  */
  8426                       while (stackp >= 0
  8427                              && STRINGP ((it->stack + stackp)->string))
  8428                         stackp--;
  8429                       if (stackp < 0)
  8430                         {
  8431                           /* If no stack slot was found for iterating
  8432                              a buffer, we are displaying text from a
  8433                              string, most probably the mode line or
  8434                              the header line, and that string has a
  8435                              display string on some of its
  8436                              characters.  */
  8437                           text_from_string = true;
  8438                           pos = it->stack[it->sp - 1].position;
  8439                         }
  8440                       else
  8441                         pos = (it->stack + stackp)->position;
  8442                     }
  8443                   else
  8444                     INC_TEXT_POS (pos, it->multibyte_p);
  8445 
  8446                   if (text_from_string)
  8447                     {
  8448                       Lisp_Object base_string = it->stack[it->sp - 1].string;
  8449 
  8450                       if (CHARPOS (pos) >= SCHARS (base_string) - 1)
  8451                         it->end_of_box_run_p = true;
  8452                       else
  8453                         {
  8454                           next_face_id
  8455                             = face_at_string_position (it->w, base_string,
  8456                                                        CHARPOS (pos), 0,
  8457                                                        &ignore, face_id,
  8458                                                        false, 0);
  8459                           if (FACE_FROM_ID (it->f, next_face_id)->box
  8460                               == FACE_NO_BOX)
  8461                             it->end_of_box_run_p = true;
  8462                         }
  8463                     }
  8464                   else if (CHARPOS (pos) >= ZV)
  8465                     it->end_of_box_run_p = true;
  8466                   else
  8467                     {
  8468                       next_face_id =
  8469                         face_at_buffer_position (it->w, CHARPOS (pos),
  8470                                                  &ignore,
  8471                                                  CHARPOS (pos)
  8472                                                  + TEXT_PROP_DISTANCE_LIMIT,
  8473                                                  false, -1, 0);
  8474                       if (FACE_FROM_ID (it->f, next_face_id)->box
  8475                           == FACE_NO_BOX)
  8476                         it->end_of_box_run_p = true;
  8477                     }
  8478                 }
  8479             }
  8480         }
  8481       /* next_element_from_display_vector sets this flag according to
  8482          faces of the display vector glyphs, see there.  */
  8483       else if (it->method != GET_FROM_DISPLAY_VECTOR)
  8484         {
  8485           int face_id = face_after_it_pos (it);
  8486           if (face_id != it->face_id
  8487               && FACE_FROM_ID (it->f, face_id)->box == FACE_NO_BOX)
  8488             it->end_of_box_run_p = true;
  8489         }
  8490     }
  8491   /* If we reached the end of the object we've been iterating (e.g., a
  8492      display string or an overlay string), and there's something on
  8493      IT->stack, proceed with what's on the stack.  It doesn't make
  8494      sense to return false if there's unprocessed stuff on the stack,
  8495      because otherwise that stuff will never be displayed.  */
  8496   if (!success_p && it->sp > 0)
  8497     {
  8498       set_iterator_to_next (it, false);
  8499       success_p = get_next_display_element (it);
  8500     }
  8501 
  8502   /* Value is false if end of buffer or string reached.  */
  8503   return success_p;
  8504 }
  8505 
  8506 
  8507 /* Move IT to the next display element.
  8508 
  8509    RESEAT_P means if called on a newline in buffer text,
  8510    skip to the next visible line start.
  8511 
  8512    Functions get_next_display_element and set_iterator_to_next are
  8513    separate because I find this arrangement easier to handle than a
  8514    get_next_display_element function that also increments IT's
  8515    position.  The way it is we can first look at an iterator's current
  8516    display element, decide whether it fits on a line, and if it does,
  8517    increment the iterator position.  The other way around we probably
  8518    would either need a flag indicating whether the iterator has to be
  8519    incremented the next time, or we would have to implement a
  8520    decrement position function which would not be easy to write.  */
  8521 
  8522 void
  8523 set_iterator_to_next (struct it *it, bool reseat_p)
  8524 {
  8525 
  8526   if (max_redisplay_ticks > 0)
  8527     update_redisplay_ticks (1, it->w);
  8528 
  8529   switch (it->method)
  8530     {
  8531     case GET_FROM_BUFFER:
  8532       /* The current display element of IT is a character from
  8533          current_buffer.  Advance in the buffer, and maybe skip over
  8534          invisible lines that are so because of selective display.  */
  8535       if (ITERATOR_AT_END_OF_LINE_P (it) && reseat_p)
  8536         reseat_at_next_visible_line_start (it, false);
  8537       else if (it->cmp_it.id >= 0)
  8538         {
  8539           /* We are currently getting glyphs from a composition.  */
  8540           if (! it->bidi_p)
  8541             {
  8542               IT_CHARPOS (*it) += it->cmp_it.nchars;
  8543               IT_BYTEPOS (*it) += it->cmp_it.nbytes;
  8544             }
  8545           else
  8546             {
  8547               int i;
  8548 
  8549               /* Update IT's char/byte positions to point to the first
  8550                  character of the next grapheme cluster, or to the
  8551                  character visually after the current composition.  */
  8552               for (i = 0; i < it->cmp_it.nchars; i++)
  8553                 bidi_move_to_visually_next (&it->bidi_it);
  8554               IT_BYTEPOS (*it) = it->bidi_it.bytepos;
  8555               IT_CHARPOS (*it) = it->bidi_it.charpos;
  8556             }
  8557 
  8558           if ((! it->bidi_p || ! it->cmp_it.reversed_p)
  8559               && it->cmp_it.to < it->cmp_it.nglyphs)
  8560             {
  8561               /* Composition created while scanning forward.  Proceed
  8562                  to the next grapheme cluster.  */
  8563               it->cmp_it.from = it->cmp_it.to;
  8564             }
  8565           else if ((it->bidi_p && it->cmp_it.reversed_p)
  8566                    && it->cmp_it.from > 0)
  8567             {
  8568               /* Composition created while scanning backward.  Proceed
  8569                  to the previous grapheme cluster.  */
  8570               it->cmp_it.to = it->cmp_it.from;
  8571             }
  8572           else
  8573             {
  8574               /* No more grapheme clusters in this composition.
  8575                  Find the next stop position.  */
  8576               ptrdiff_t stop = it->end_charpos;
  8577 
  8578               if (it->bidi_it.scan_dir < 0)
  8579                 /* Now we are scanning backward and don't know
  8580                    where to stop.  */
  8581                 stop = -1;
  8582               composition_compute_stop_pos (&it->cmp_it, IT_CHARPOS (*it),
  8583                                             IT_BYTEPOS (*it), stop, Qnil, true);
  8584             }
  8585         }
  8586       else
  8587         {
  8588           eassert (it->len != 0);
  8589 
  8590           if (!it->bidi_p)
  8591             {
  8592               IT_BYTEPOS (*it) += it->len;
  8593               IT_CHARPOS (*it) += 1;
  8594             }
  8595           else
  8596             {
  8597               int prev_scan_dir = it->bidi_it.scan_dir;
  8598               /* If this is a new paragraph, determine its base
  8599                  direction (a.k.a. its base embedding level).  */
  8600               if (it->bidi_it.new_paragraph)
  8601                 bidi_paragraph_init (it->paragraph_embedding, &it->bidi_it,
  8602                                      false);
  8603               bidi_move_to_visually_next (&it->bidi_it);
  8604               IT_BYTEPOS (*it) = it->bidi_it.bytepos;
  8605               IT_CHARPOS (*it) = it->bidi_it.charpos;
  8606               if (prev_scan_dir != it->bidi_it.scan_dir)
  8607                 {
  8608                   /* As the scan direction was changed, we must
  8609                      re-compute the stop position for composition.  */
  8610                   ptrdiff_t stop = it->end_charpos;
  8611                   if (it->bidi_it.scan_dir < 0)
  8612                     stop = -1;
  8613                   composition_compute_stop_pos (&it->cmp_it, IT_CHARPOS (*it),
  8614                                                 IT_BYTEPOS (*it), stop, Qnil,
  8615                                                 true);
  8616                 }
  8617             }
  8618           eassert (IT_BYTEPOS (*it) == CHAR_TO_BYTE (IT_CHARPOS (*it)));
  8619         }
  8620       break;
  8621 
  8622     case GET_FROM_C_STRING:
  8623       /* Current display element of IT is from a C string.  */
  8624       if (!it->bidi_p
  8625           /* If the string position is beyond string's end, it means
  8626              next_element_from_c_string is padding the string with
  8627              blanks, in which case we bypass the bidi iterator,
  8628              because it cannot deal with such virtual characters.  */
  8629           || IT_CHARPOS (*it) >= it->bidi_it.string.schars)
  8630         {
  8631           IT_BYTEPOS (*it) += it->len;
  8632           IT_CHARPOS (*it) += 1;
  8633         }
  8634       else
  8635         {
  8636           bidi_move_to_visually_next (&it->bidi_it);
  8637           IT_BYTEPOS (*it) = it->bidi_it.bytepos;
  8638           IT_CHARPOS (*it) = it->bidi_it.charpos;
  8639         }
  8640       break;
  8641 
  8642     case GET_FROM_DISPLAY_VECTOR:
  8643       /* Current display element of IT is from a display table entry.
  8644          Advance in the display table definition.  Reset it to null if
  8645          end reached, and continue with characters from buffers/
  8646          strings.  */
  8647       ++it->current.dpvec_index;
  8648 
  8649       /* Restore face of the iterator to what they were before the
  8650          display vector entry (these entries may contain faces).  */
  8651       it->face_id = it->saved_face_id;
  8652 
  8653       if (it->dpvec + it->current.dpvec_index >= it->dpend)
  8654         {
  8655           bool recheck_faces = it->ellipsis_p;
  8656 
  8657           if (it->s)
  8658             it->method = GET_FROM_C_STRING;
  8659           else if (STRINGP (it->string))
  8660             it->method = GET_FROM_STRING;
  8661           else
  8662             {
  8663               it->method = GET_FROM_BUFFER;
  8664               it->object = it->w->contents;
  8665             }
  8666 
  8667           it->dpvec = NULL;
  8668           it->current.dpvec_index = -1;
  8669 
  8670           /* Skip over characters which were displayed via IT->dpvec.  */
  8671           if (it->dpvec_char_len < 0)
  8672             reseat_at_next_visible_line_start (it, true);
  8673           else if (it->dpvec_char_len > 0)
  8674             {
  8675               it->len = it->dpvec_char_len;
  8676               set_iterator_to_next (it, reseat_p);
  8677             }
  8678 
  8679           /* Maybe recheck faces after display vector.  */
  8680           if (recheck_faces)
  8681             {
  8682               if (it->method == GET_FROM_STRING)
  8683                 it->stop_charpos = IT_STRING_CHARPOS (*it);
  8684               else
  8685                 it->stop_charpos = IT_CHARPOS (*it);
  8686             }
  8687         }
  8688       break;
  8689 
  8690     case GET_FROM_STRING:
  8691       /* Current display element is a character from a Lisp string.  */
  8692       eassert (it->s == NULL && STRINGP (it->string));
  8693       /* Don't advance past string end.  These conditions are true
  8694          when set_iterator_to_next is called at the end of
  8695          get_next_display_element, in which case the Lisp string is
  8696          already exhausted, and all we want is pop the iterator
  8697          stack.  */
  8698       if (it->current.overlay_string_index >= 0)
  8699         {
  8700           /* This is an overlay string, so there's no padding with
  8701              spaces, and the number of characters in the string is
  8702              where the string ends.  */
  8703           if (IT_STRING_CHARPOS (*it) >= SCHARS (it->string))
  8704             goto consider_string_end;
  8705         }
  8706       else
  8707         {
  8708           /* Not an overlay string.  There could be padding, so test
  8709              against it->end_charpos.  */
  8710           if (IT_STRING_CHARPOS (*it) >= it->end_charpos)
  8711             goto consider_string_end;
  8712         }
  8713       if (it->cmp_it.id >= 0)
  8714         {
  8715           /* We are delivering display elements from a composition.
  8716              Update the string position past the grapheme cluster
  8717              we've just processed.  */
  8718           if (! it->bidi_p)
  8719             {
  8720               IT_STRING_CHARPOS (*it) += it->cmp_it.nchars;
  8721               IT_STRING_BYTEPOS (*it) += it->cmp_it.nbytes;
  8722             }
  8723           else
  8724             {
  8725               int i;
  8726 
  8727               for (i = 0; i < it->cmp_it.nchars; i++)
  8728                 bidi_move_to_visually_next (&it->bidi_it);
  8729               IT_STRING_BYTEPOS (*it) = it->bidi_it.bytepos;
  8730               IT_STRING_CHARPOS (*it) = it->bidi_it.charpos;
  8731             }
  8732 
  8733           /* Did we exhaust all the grapheme clusters of this
  8734              composition?  */
  8735           if ((! it->bidi_p || ! it->cmp_it.reversed_p)
  8736               && (it->cmp_it.to < it->cmp_it.nglyphs))
  8737             {
  8738               /* Not all the grapheme clusters were processed yet;
  8739                  advance to the next cluster.  */
  8740               it->cmp_it.from = it->cmp_it.to;
  8741             }
  8742           else if ((it->bidi_p && it->cmp_it.reversed_p)
  8743                    && it->cmp_it.from > 0)
  8744             {
  8745               /* Likewise: advance to the next cluster, but going in
  8746                  the reverse direction.  */
  8747               it->cmp_it.to = it->cmp_it.from;
  8748             }
  8749           else
  8750             {
  8751               /* This composition was fully processed; find the next
  8752                  candidate place for checking for composed
  8753                  characters.  */
  8754               /* Always limit string searches to the string length;
  8755                  any padding spaces are not part of the string, and
  8756                  there cannot be any compositions in that padding.  */
  8757               ptrdiff_t stop = SCHARS (it->string);
  8758 
  8759               if (it->bidi_p && it->bidi_it.scan_dir < 0)
  8760                 stop = -1;
  8761               else if (it->end_charpos < stop)
  8762                 {
  8763                   /* Cf. PRECISION in reseat_to_string: we might be
  8764                      limited in how many of the string characters we
  8765                      need to deliver.  */
  8766                   stop = it->end_charpos;
  8767                 }
  8768               composition_compute_stop_pos (&it->cmp_it,
  8769                                             IT_STRING_CHARPOS (*it),
  8770                                             IT_STRING_BYTEPOS (*it), stop,
  8771                                             it->string, true);
  8772             }
  8773         }
  8774       else
  8775         {
  8776           if (!it->bidi_p
  8777               /* If the string position is beyond string's end, it
  8778                  means next_element_from_string is padding the string
  8779                  with blanks, in which case we bypass the bidi
  8780                  iterator, because it cannot deal with such virtual
  8781                  characters.  */
  8782               || IT_STRING_CHARPOS (*it) >= it->bidi_it.string.schars)
  8783             {
  8784               IT_STRING_BYTEPOS (*it) += it->len;
  8785               IT_STRING_CHARPOS (*it) += 1;
  8786             }
  8787           else
  8788             {
  8789               int prev_scan_dir = it->bidi_it.scan_dir;
  8790 
  8791               bidi_move_to_visually_next (&it->bidi_it);
  8792               IT_STRING_BYTEPOS (*it) = it->bidi_it.bytepos;
  8793               IT_STRING_CHARPOS (*it) = it->bidi_it.charpos;
  8794               /* If the scan direction changes, we may need to update
  8795                  the place where to check for composed characters.  */
  8796               if (prev_scan_dir != it->bidi_it.scan_dir)
  8797                 {
  8798                   ptrdiff_t stop = SCHARS (it->string);
  8799 
  8800                   if (it->bidi_it.scan_dir < 0)
  8801                     stop = -1;
  8802                   else if (it->end_charpos < stop)
  8803                     stop = it->end_charpos;
  8804 
  8805                   composition_compute_stop_pos (&it->cmp_it,
  8806                                                 IT_STRING_CHARPOS (*it),
  8807                                                 IT_STRING_BYTEPOS (*it), stop,
  8808                                                 it->string, true);
  8809                 }
  8810             }
  8811         }
  8812 
  8813     consider_string_end:
  8814 
  8815       if (it->current.overlay_string_index >= 0)
  8816         {
  8817           /* IT->string is an overlay string.  Advance to the
  8818              next, if there is one.  */
  8819           if (IT_STRING_CHARPOS (*it) >= SCHARS (it->string))
  8820             {
  8821               it->ellipsis_p = false;
  8822               next_overlay_string (it);
  8823               if (it->ellipsis_p)
  8824                 setup_for_ellipsis (it, 0);
  8825             }
  8826         }
  8827       else
  8828         {
  8829           /* IT->string is not an overlay string.  If we reached
  8830              its end, and there is something on IT->stack, proceed
  8831              with what is on the stack.  This can be either another
  8832              string, this time an overlay string, or a buffer.  */
  8833           if (IT_STRING_CHARPOS (*it) == SCHARS (it->string)
  8834               && it->sp > 0)
  8835             {
  8836               pop_it (it);
  8837               if (it->method == GET_FROM_STRING)
  8838                 goto consider_string_end;
  8839             }
  8840         }
  8841       break;
  8842 
  8843     case GET_FROM_IMAGE:
  8844     case GET_FROM_STRETCH:
  8845     case GET_FROM_XWIDGET:
  8846 
  8847       /* The position etc with which we have to proceed are on
  8848          the stack.  The position may be at the end of a string,
  8849          if the `display' property takes up the whole string.  */
  8850       eassert (it->sp > 0);
  8851       pop_it (it);
  8852       if (it->method == GET_FROM_STRING)
  8853         goto consider_string_end;
  8854       break;
  8855 
  8856     default:
  8857       /* There are no other methods defined, so this should be a bug.  */
  8858       emacs_abort ();
  8859     }
  8860 
  8861   eassert (it->method != GET_FROM_STRING
  8862            || (STRINGP (it->string)
  8863                && IT_STRING_CHARPOS (*it) >= 0));
  8864 }
  8865 
  8866 /* Load IT's display element fields with information about the next
  8867    display element which comes from a display table entry or from the
  8868    result of translating a control character to one of the forms `^C'
  8869    or `\003'.
  8870 
  8871    IT->dpvec holds the glyphs to return as characters.
  8872    IT->saved_face_id holds the face id before the display vector--it
  8873    is restored into IT->face_id in set_iterator_to_next.  */
  8874 
  8875 static bool
  8876 next_element_from_display_vector (struct it *it)
  8877 {
  8878   Lisp_Object gc;
  8879   int prev_face_id = it->face_id;
  8880   int next_face_id;
  8881 
  8882   /* Precondition.  */
  8883   eassert (it->dpvec && it->current.dpvec_index >= 0);
  8884 
  8885   it->face_id = it->saved_face_id;
  8886 
  8887   /* KFS: This code used to check ip->dpvec[0] instead of the current element.
  8888      That seemed totally bogus - so I changed it...  */
  8889   if (it->dpend - it->dpvec > 0 /* empty dpvec[] is invalid */
  8890       && (gc = it->dpvec[it->current.dpvec_index], GLYPH_CODE_P (gc)))
  8891     {
  8892       struct face *this_face, *prev_face, *next_face;
  8893 
  8894       it->c = GLYPH_CODE_CHAR (gc);
  8895       it->len = CHAR_BYTES (it->c);
  8896 
  8897       /* The entry may contain a face id to use.  Such a face id is
  8898          the id of a Lisp face, not a realized face.  A face id of
  8899          zero means no face is specified.  */
  8900       if (it->dpvec_face_id >= 0)
  8901         it->face_id = it->dpvec_face_id;
  8902       else
  8903         {
  8904           int lface_id = GLYPH_CODE_FACE (gc);
  8905           if (lface_id > 0)
  8906             it->face_id = merge_faces (it->w, Qt, lface_id,
  8907                                        it->saved_face_id);
  8908         }
  8909 
  8910       /* Glyphs in the display vector could have the box face, so we
  8911          need to set the related flags in the iterator, as
  8912          appropriate.  */
  8913       this_face = FACE_FROM_ID_OR_NULL (it->f, it->face_id);
  8914       prev_face = FACE_FROM_ID_OR_NULL (it->f, prev_face_id);
  8915 
  8916       /* Is this character the first character of a box-face run?  */
  8917       it->start_of_box_run_p = (this_face && this_face->box != FACE_NO_BOX
  8918                                 && (!prev_face
  8919                                     || prev_face->box == FACE_NO_BOX));
  8920 
  8921       /* For the last character of the box-face run, we need to look
  8922          either at the next glyph from the display vector, or at the
  8923          face we saw before the display vector.  */
  8924       next_face_id = it->saved_face_id;
  8925       if (it->current.dpvec_index < it->dpend - it->dpvec - 1)
  8926         {
  8927           if (it->dpvec_face_id >= 0)
  8928             next_face_id = it->dpvec_face_id;
  8929           else
  8930             {
  8931               Lisp_Object gc = it->dpvec[it->current.dpvec_index + 1];
  8932               int lface_id = GLYPH_CODE_P (gc) ? GLYPH_CODE_FACE (gc) : 0;
  8933 
  8934               if (lface_id > 0)
  8935                 next_face_id = merge_faces (it->w, Qt, lface_id,
  8936                                             it->saved_face_id);
  8937             }
  8938         }
  8939       next_face = FACE_FROM_ID_OR_NULL (it->f, next_face_id);
  8940       if (this_face && this_face->box != FACE_NO_BOX
  8941           && (!next_face || next_face->box == FACE_NO_BOX))
  8942         it->end_of_box_run_p = true;
  8943       it->face_box_p = this_face && this_face->box != FACE_NO_BOX;
  8944     }
  8945   else
  8946     /* Display table entry is invalid.  Return a space.  */
  8947     it->c = ' ', it->len = 1;
  8948 
  8949   /* Don't change position and object of the iterator here.  They are
  8950      still the values of the character that had this display table
  8951      entry or was translated, and that's what we want.  */
  8952   it->what = IT_CHARACTER;
  8953   return true;
  8954 }
  8955 
  8956 /* Get the first element of string/buffer in the visual order, after
  8957    being reseated to a new position in a string or a buffer.  */
  8958 static void
  8959 get_visually_first_element (struct it *it)
  8960 {
  8961   bool string_p = STRINGP (it->string) || it->s;
  8962   ptrdiff_t eob = (string_p ? it->bidi_it.string.schars : ZV);
  8963   ptrdiff_t bob;
  8964   ptrdiff_t obegv = BEGV;
  8965 
  8966   SET_WITH_NARROWED_BEGV (it, bob,
  8967                           string_p ? 0 :
  8968                           IT_CHARPOS (*it) < BEGV ? obegv : BEGV,
  8969                           it->medium_narrowing_begv);
  8970 
  8971   if (STRINGP (it->string))
  8972     {
  8973       it->bidi_it.charpos = IT_STRING_CHARPOS (*it);
  8974       it->bidi_it.bytepos = IT_STRING_BYTEPOS (*it);
  8975     }
  8976   else
  8977     {
  8978       it->bidi_it.charpos = IT_CHARPOS (*it);
  8979       it->bidi_it.bytepos = IT_BYTEPOS (*it);
  8980     }
  8981 
  8982   if (it->bidi_it.charpos == eob)
  8983     {
  8984       /* Nothing to do, but reset the FIRST_ELT flag, like
  8985          bidi_paragraph_init does, because we are not going to
  8986          call it.  */
  8987       it->bidi_it.first_elt = false;
  8988     }
  8989   else if (it->bidi_it.charpos == bob
  8990            || (!string_p
  8991                && (FETCH_BYTE (it->bidi_it.bytepos - 1) == '\n'
  8992                    || FETCH_BYTE (it->bidi_it.bytepos) == '\n')))
  8993     {
  8994       /* If we are at the beginning of a line/string, we can produce
  8995          the next element right away.  */
  8996       bidi_paragraph_init (it->paragraph_embedding, &it->bidi_it, true);
  8997       bidi_move_to_visually_next (&it->bidi_it);
  8998     }
  8999   else
  9000     {
  9001       ptrdiff_t orig_bytepos = it->bidi_it.bytepos;
  9002 
  9003       /* We need to prime the bidi iterator starting at the line's or
  9004          string's beginning, before we will be able to produce the
  9005          next element.  */
  9006       if (string_p)
  9007         it->bidi_it.charpos = it->bidi_it.bytepos = 0;
  9008       else
  9009         SET_WITH_NARROWED_BEGV (it, it->bidi_it.charpos,
  9010                                 find_newline_no_quit (IT_CHARPOS (*it),
  9011                                                       IT_BYTEPOS (*it), -1,
  9012                                                       &it->bidi_it.bytepos),
  9013                                 it->medium_narrowing_begv);
  9014       bidi_paragraph_init (it->paragraph_embedding, &it->bidi_it, true);
  9015       do
  9016         {
  9017           /* Now return to buffer/string position where we were asked
  9018              to get the next display element, and produce that.  */
  9019           bidi_move_to_visually_next (&it->bidi_it);
  9020         }
  9021       while (it->bidi_it.bytepos != orig_bytepos
  9022              && it->bidi_it.charpos < eob);
  9023     }
  9024 
  9025   /*  Adjust IT's position information to where we ended up.  */
  9026   if (STRINGP (it->string))
  9027     {
  9028       IT_STRING_CHARPOS (*it) = it->bidi_it.charpos;
  9029       IT_STRING_BYTEPOS (*it) = it->bidi_it.bytepos;
  9030     }
  9031   else
  9032     {
  9033       IT_CHARPOS (*it) = it->bidi_it.charpos;
  9034       IT_BYTEPOS (*it) = it->bidi_it.bytepos;
  9035     }
  9036 
  9037   if (STRINGP (it->string) || !it->s)
  9038     {
  9039       ptrdiff_t stop, charpos, bytepos;
  9040 
  9041       if (STRINGP (it->string))
  9042         {
  9043           eassert (!it->s);
  9044           stop = SCHARS (it->string);
  9045           if (stop > it->end_charpos)
  9046             stop = it->end_charpos;
  9047           charpos = IT_STRING_CHARPOS (*it);
  9048           bytepos = IT_STRING_BYTEPOS (*it);
  9049         }
  9050       else
  9051         {
  9052           stop = it->end_charpos;
  9053           charpos = IT_CHARPOS (*it);
  9054           bytepos = IT_BYTEPOS (*it);
  9055         }
  9056       if (it->bidi_it.scan_dir < 0)
  9057         stop = -1;
  9058       composition_compute_stop_pos (&it->cmp_it, charpos, bytepos, stop,
  9059                                     it->string, true);
  9060     }
  9061 }
  9062 
  9063 /* Load IT with the next display element from Lisp string IT->string.
  9064    IT->current.string_pos is the current position within the string.
  9065    If IT->current.overlay_string_index >= 0, the Lisp string is an
  9066    overlay string.  */
  9067 
  9068 static bool
  9069 next_element_from_string (struct it *it)
  9070 {
  9071   struct text_pos position;
  9072 
  9073   eassert (STRINGP (it->string));
  9074   eassert (!it->bidi_p || EQ (it->string, it->bidi_it.string.lstring));
  9075   eassert (IT_STRING_CHARPOS (*it) >= 0);
  9076   position = it->current.string_pos;
  9077 
  9078   /* With bidi reordering, the character to display might not be the
  9079      character at IT_STRING_CHARPOS.  BIDI_IT.FIRST_ELT means
  9080      that we were reseat()ed to a new string, whose paragraph
  9081      direction is not known.  */
  9082   if (it->bidi_p && it->bidi_it.first_elt)
  9083     {
  9084       get_visually_first_element (it);
  9085       SET_TEXT_POS (position, IT_STRING_CHARPOS (*it), IT_STRING_BYTEPOS (*it));
  9086     }
  9087 
  9088   /* Time to check for invisible text?  */
  9089   if (IT_STRING_CHARPOS (*it) < it->end_charpos)
  9090     {
  9091       if (IT_STRING_CHARPOS (*it) >= it->stop_charpos)
  9092         {
  9093           if (!(!it->bidi_p
  9094                 || BIDI_AT_BASE_LEVEL (it->bidi_it)
  9095                 || IT_STRING_CHARPOS (*it) == it->stop_charpos))
  9096             {
  9097               /* With bidi non-linear iteration, we could find
  9098                  ourselves far beyond the last computed stop_charpos,
  9099                  with several other stop positions in between that we
  9100                  missed.  Scan them all now, in buffer's logical
  9101                  order, until we find and handle the last stop_charpos
  9102                  that precedes our current position.  */
  9103               handle_stop_backwards (it, it->stop_charpos);
  9104               return GET_NEXT_DISPLAY_ELEMENT (it);
  9105             }
  9106           else
  9107             {
  9108               if (it->bidi_p)
  9109                 {
  9110                   /* Take note of the stop position we just moved
  9111                      across, for when we will move back across it.  */
  9112                   it->prev_stop = it->stop_charpos;
  9113                   /* If we are at base paragraph embedding level, take
  9114                      note of the last stop position seen at this
  9115                      level.  */
  9116                   if (BIDI_AT_BASE_LEVEL (it->bidi_it))
  9117                     it->base_level_stop = it->stop_charpos;
  9118                 }
  9119               handle_stop (it);
  9120 
  9121               /* Since a handler may have changed IT->method, we must
  9122                  recurse here.  */
  9123               return GET_NEXT_DISPLAY_ELEMENT (it);
  9124             }
  9125         }
  9126       else if (it->bidi_p
  9127                /* If we are before prev_stop, we may have overstepped
  9128                   on our way backwards a stop_pos, and if so, we need
  9129                   to handle that stop_pos.  */
  9130                && IT_STRING_CHARPOS (*it) < it->prev_stop
  9131                /* We can sometimes back up for reasons that have nothing
  9132                   to do with bidi reordering.  E.g., compositions.  The
  9133                   code below is only needed when we are above the base
  9134                   embedding level, so test for that explicitly.  */
  9135                && !BIDI_AT_BASE_LEVEL (it->bidi_it))
  9136         {
  9137           /* If we lost track of base_level_stop, we have no better
  9138              place for handle_stop_backwards to start from than string
  9139              beginning.  This happens, e.g., when we were reseated to
  9140              the previous screenful of text by vertical-motion.  */
  9141           if (it->base_level_stop <= 0
  9142               || IT_STRING_CHARPOS (*it) < it->base_level_stop)
  9143             it->base_level_stop = 0;
  9144           handle_stop_backwards (it, it->base_level_stop);
  9145           return GET_NEXT_DISPLAY_ELEMENT (it);
  9146         }
  9147     }
  9148 
  9149   if (it->current.overlay_string_index >= 0)
  9150     {
  9151       /* Get the next character from an overlay string.  In overlay
  9152          strings, there is no field width or padding with spaces to
  9153          do.  */
  9154       if (IT_STRING_CHARPOS (*it) >= SCHARS (it->string))
  9155         {
  9156           it->what = IT_EOB;
  9157           return false;
  9158         }
  9159       else if (CHAR_COMPOSED_P (it, IT_STRING_CHARPOS (*it),
  9160                                 IT_STRING_BYTEPOS (*it),
  9161                                 it->bidi_it.scan_dir < 0
  9162                                 ? -1
  9163                                 : SCHARS (it->string))
  9164                && next_element_from_composition (it))
  9165         {
  9166           return true;
  9167         }
  9168       else if (STRING_MULTIBYTE (it->string))
  9169         {
  9170           const unsigned char *s = (SDATA (it->string)
  9171                                     + IT_STRING_BYTEPOS (*it));
  9172           it->c = check_char_and_length (s, &it->len);
  9173         }
  9174       else
  9175         {
  9176           it->c = SREF (it->string, IT_STRING_BYTEPOS (*it));
  9177           it->len = 1;
  9178         }
  9179     }
  9180   else
  9181     {
  9182       /* Get the next character from a Lisp string that is not an
  9183          overlay string.  Such strings come from the mode line, for
  9184          example.  We may have to pad with spaces, or truncate the
  9185          string.  See also next_element_from_c_string.  */
  9186       if (IT_STRING_CHARPOS (*it) >= it->end_charpos)
  9187         {
  9188           it->what = IT_EOB;
  9189           return false;
  9190         }
  9191       else if (IT_STRING_CHARPOS (*it) >= it->string_nchars)
  9192         {
  9193           /* Pad with spaces.  */
  9194           it->c = ' ', it->len = 1;
  9195           CHARPOS (position) = BYTEPOS (position) = -1;
  9196         }
  9197       else if (CHAR_COMPOSED_P (it, IT_STRING_CHARPOS (*it),
  9198                                 IT_STRING_BYTEPOS (*it),
  9199                                 it->bidi_it.scan_dir < 0
  9200                                 ? -1
  9201                                 : it->string_nchars)
  9202                && next_element_from_composition (it))
  9203         {
  9204           return true;
  9205         }
  9206       else if (STRING_MULTIBYTE (it->string))
  9207         {
  9208           const unsigned char *s = (SDATA (it->string)
  9209                                     + IT_STRING_BYTEPOS (*it));
  9210           it->c = check_char_and_length (s, &it->len);
  9211         }
  9212       else
  9213         {
  9214           it->c = SREF (it->string, IT_STRING_BYTEPOS (*it));
  9215           it->len = 1;
  9216         }
  9217     }
  9218 
  9219   /* Record what we have and where it came from.  */
  9220   it->what = IT_CHARACTER;
  9221   it->object = it->string;
  9222   it->position = position;
  9223   return true;
  9224 }
  9225 
  9226 
  9227 /* Load IT with next display element from C string IT->s.
  9228    IT->string_nchars is the maximum number of characters to return
  9229    from the string.  IT->end_charpos may be greater than
  9230    IT->string_nchars when this function is called, in which case we
  9231    may have to return padding spaces.  Value is false if end of string
  9232    reached, including padding spaces.  */
  9233 
  9234 static bool
  9235 next_element_from_c_string (struct it *it)
  9236 {
  9237   bool success_p = true;
  9238 
  9239   eassert (it->s);
  9240   eassert (!it->bidi_p || it->s == it->bidi_it.string.s);
  9241   it->what = IT_CHARACTER;
  9242   BYTEPOS (it->position) = CHARPOS (it->position) = 0;
  9243   it->object = make_fixnum (0);
  9244 
  9245   /* With bidi reordering, the character to display might not be the
  9246      character at IT_CHARPOS.  BIDI_IT.FIRST_ELT means that
  9247      we were reseated to a new string, whose paragraph direction is
  9248      not known.  */
  9249   if (it->bidi_p && it->bidi_it.first_elt)
  9250     get_visually_first_element (it);
  9251 
  9252   /* IT's position can be greater than IT->string_nchars in case a
  9253      field width or precision has been specified when the iterator was
  9254      initialized.  */
  9255   if (IT_CHARPOS (*it) >= it->end_charpos)
  9256     {
  9257       /* End of the game.  */
  9258       it->what = IT_EOB;
  9259       success_p = false;
  9260     }
  9261   else if (IT_CHARPOS (*it) >= it->string_nchars)
  9262     {
  9263       /* Pad with spaces.  */
  9264       it->c = ' ', it->len = 1;
  9265       BYTEPOS (it->position) = CHARPOS (it->position) = -1;
  9266     }
  9267   else if (it->multibyte_p)
  9268     it->c = check_char_and_length (it->s + IT_BYTEPOS (*it), &it->len);
  9269   else
  9270     it->c = it->s[IT_BYTEPOS (*it)], it->len = 1;
  9271 
  9272   return success_p;
  9273 }
  9274 
  9275 
  9276 /* Set up IT to return characters from an ellipsis, if appropriate.
  9277    The definition of the ellipsis glyphs may come from a display table
  9278    entry.  This function fills IT with the first glyph from the
  9279    ellipsis if an ellipsis is to be displayed.  */
  9280 
  9281 static bool
  9282 next_element_from_ellipsis (struct it *it)
  9283 {
  9284   if (it->selective_display_ellipsis_p)
  9285     setup_for_ellipsis (it, it->len);
  9286   else
  9287     {
  9288       /* The face at the current position may be different from the
  9289          face we find after the invisible text.  Remember what it
  9290          was in IT->saved_face_id, and signal that it's there by
  9291          setting face_before_selective_p.  */
  9292       it->saved_face_id = it->face_id;
  9293       it->method = GET_FROM_BUFFER;
  9294       it->object = it->w->contents;
  9295       reseat_at_next_visible_line_start (it, true);
  9296       it->face_before_selective_p = true;
  9297     }
  9298 
  9299   return GET_NEXT_DISPLAY_ELEMENT (it);
  9300 }
  9301 
  9302 
  9303 /* Deliver an image display element.  The iterator IT is already
  9304    filled with image information (done in handle_display_prop).  Value
  9305    is always true.  */
  9306 
  9307 
  9308 static bool
  9309 next_element_from_image (struct it *it)
  9310 {
  9311   it->what = IT_IMAGE;
  9312   return true;
  9313 }
  9314 
  9315 static bool
  9316 next_element_from_xwidget (struct it *it)
  9317 {
  9318   it->what = IT_XWIDGET;
  9319   return true;
  9320 }
  9321 
  9322 
  9323 /* Fill iterator IT with next display element from a stretch glyph
  9324    property.  IT->object is the value of the text property.  Value is
  9325    always true.  */
  9326 
  9327 static bool
  9328 next_element_from_stretch (struct it *it)
  9329 {
  9330   it->what = IT_STRETCH;
  9331   return true;
  9332 }
  9333 
  9334 /* Scan backwards from IT's current position until we find a stop
  9335    position, or until BEGV.  This is called when we find ourself
  9336    before both the last known prev_stop and base_level_stop while
  9337    reordering bidirectional text.  */
  9338 
  9339 static void
  9340 compute_stop_pos_backwards (struct it *it)
  9341 {
  9342   const int SCAN_BACK_LIMIT = 1000;
  9343   struct text_pos pos;
  9344   struct display_pos save_current = it->current;
  9345   struct text_pos save_position = it->position;
  9346   ptrdiff_t charpos = IT_CHARPOS (*it);
  9347   ptrdiff_t where_we_are = charpos;
  9348   ptrdiff_t save_stop_pos = it->stop_charpos;
  9349   ptrdiff_t save_end_pos = it->end_charpos;
  9350 
  9351   eassert (NILP (it->string) && !it->s);
  9352   eassert (it->bidi_p);
  9353   it->bidi_p = false;
  9354   do
  9355     {
  9356       it->end_charpos = min (charpos + 1, ZV);
  9357       charpos = max (charpos - SCAN_BACK_LIMIT, BEGV);
  9358       SET_TEXT_POS (pos, charpos, CHAR_TO_BYTE (charpos));
  9359       reseat_1 (it, pos, false);
  9360       compute_stop_pos (it);
  9361       /* We must advance forward, right?  */
  9362       if (it->stop_charpos <= charpos)
  9363         emacs_abort ();
  9364     }
  9365   while (charpos > BEGV && it->stop_charpos >= it->end_charpos);
  9366 
  9367   if (it->stop_charpos <= where_we_are)
  9368     it->prev_stop = it->stop_charpos;
  9369   else
  9370     it->prev_stop = BEGV;
  9371   it->bidi_p = true;
  9372   it->current = save_current;
  9373   it->position = save_position;
  9374   it->stop_charpos = save_stop_pos;
  9375   it->end_charpos = save_end_pos;
  9376 }
  9377 
  9378 /* Scan forward from CHARPOS in the current buffer/string, until we
  9379    find a stop position > current IT's position.  Then handle the stop
  9380    position before that.  This is called when we bump into a stop
  9381    position while reordering bidirectional text.  CHARPOS should be
  9382    the last previously processed stop_pos (or BEGV/0, if none were
  9383    processed yet) whose position is less than IT's current
  9384    position.  */
  9385 
  9386 static void
  9387 handle_stop_backwards (struct it *it, ptrdiff_t charpos)
  9388 {
  9389   bool bufp = !STRINGP (it->string);
  9390   ptrdiff_t where_we_are = (bufp ? IT_CHARPOS (*it) : IT_STRING_CHARPOS (*it));
  9391   struct display_pos save_current = it->current;
  9392   struct text_pos save_position = it->position;
  9393   struct composition_it save_cmp_it = it->cmp_it;
  9394   struct text_pos pos1;
  9395   ptrdiff_t next_stop;
  9396 
  9397   /* Scan in strict logical order.  */
  9398   eassert (it->bidi_p);
  9399   it->bidi_p = false;
  9400   do
  9401     {
  9402       it->prev_stop = charpos;
  9403       if (bufp)
  9404         {
  9405           SET_TEXT_POS (pos1, charpos, CHAR_TO_BYTE (charpos));
  9406           reseat_1 (it, pos1, false);
  9407         }
  9408       else
  9409         it->current.string_pos = string_pos (charpos, it->string);
  9410       compute_stop_pos (it);
  9411       /* We must advance forward, right?  */
  9412       if (it->stop_charpos <= it->prev_stop)
  9413         emacs_abort ();
  9414       charpos = it->stop_charpos;
  9415     }
  9416   while (charpos <= where_we_are);
  9417 
  9418   it->bidi_p = true;
  9419   it->current = save_current;
  9420   it->position = save_position;
  9421   it->cmp_it = save_cmp_it;
  9422   next_stop = it->stop_charpos;
  9423   it->stop_charpos = it->prev_stop;
  9424   handle_stop (it);
  9425   it->stop_charpos = next_stop;
  9426 }
  9427 
  9428 /* Load IT with the next display element from current_buffer.  Value
  9429    is false if end of buffer reached.  IT->stop_charpos is the next
  9430    position at which to stop and check for text properties or buffer
  9431    end.  */
  9432 
  9433 static bool
  9434 next_element_from_buffer (struct it *it)
  9435 {
  9436   bool success_p = true;
  9437 
  9438   eassert (IT_CHARPOS (*it) >= BEGV);
  9439   eassert (NILP (it->string) && !it->s);
  9440   eassert (!it->bidi_p
  9441            || (NILP (it->bidi_it.string.lstring)
  9442                && it->bidi_it.string.s == NULL));
  9443 
  9444   /* With bidi reordering, the character to display might not be the
  9445      character at IT_CHARPOS.  BIDI_IT.FIRST_ELT means that
  9446      we were reseat()ed to a new buffer position, which is potentially
  9447      a different paragraph.  */
  9448   if (it->bidi_p && it->bidi_it.first_elt)
  9449     {
  9450       get_visually_first_element (it);
  9451       SET_TEXT_POS (it->position, IT_CHARPOS (*it), IT_BYTEPOS (*it));
  9452     }
  9453 
  9454   if (IT_CHARPOS (*it) >= it->stop_charpos)
  9455     {
  9456       if (IT_CHARPOS (*it) >= it->end_charpos)
  9457         {
  9458           bool overlay_strings_follow_p;
  9459 
  9460           /* End of the game, except when overlay strings follow that
  9461              haven't been returned yet.  */
  9462           if (it->overlay_strings_at_end_processed_p)
  9463             overlay_strings_follow_p = false;
  9464           else
  9465             {
  9466               it->overlay_strings_at_end_processed_p = true;
  9467               overlay_strings_follow_p = get_overlay_strings (it, 0);
  9468             }
  9469 
  9470           if (overlay_strings_follow_p)
  9471             success_p = GET_NEXT_DISPLAY_ELEMENT (it);
  9472           else
  9473             {
  9474               it->what = IT_EOB;
  9475               it->position = it->current.pos;
  9476               success_p = false;
  9477             }
  9478         }
  9479       else if (!(!it->bidi_p
  9480                  || BIDI_AT_BASE_LEVEL (it->bidi_it)
  9481                  || IT_CHARPOS (*it) == it->stop_charpos))
  9482         {
  9483           /* With bidi non-linear iteration, we could find ourselves
  9484              far beyond the last computed stop_charpos, with several
  9485              other stop positions in between that we missed.  Scan
  9486              them all now, in buffer's logical order, until we find
  9487              and handle the last stop_charpos that precedes our
  9488              current position.  */
  9489           handle_stop_backwards (it, it->stop_charpos);
  9490           it->ignore_overlay_strings_at_pos_p = false;
  9491           return GET_NEXT_DISPLAY_ELEMENT (it);
  9492         }
  9493       else
  9494         {
  9495           if (it->bidi_p)
  9496             {
  9497               /* Take note of the stop position we just moved across,
  9498                  for when we will move back across it.  */
  9499               it->prev_stop = it->stop_charpos;
  9500               /* If we are at base paragraph embedding level, take
  9501                  note of the last stop position seen at this
  9502                  level.  */
  9503               if (BIDI_AT_BASE_LEVEL (it->bidi_it))
  9504                 it->base_level_stop = it->stop_charpos;
  9505             }
  9506           handle_stop (it);
  9507           it->ignore_overlay_strings_at_pos_p = false;
  9508           return GET_NEXT_DISPLAY_ELEMENT (it);
  9509         }
  9510     }
  9511   else if (it->bidi_p
  9512            /* If we are before prev_stop, we may have overstepped on
  9513               our way backwards a stop_pos, and if so, we need to
  9514               handle that stop_pos.  */
  9515            && IT_CHARPOS (*it) < it->prev_stop
  9516            /* We can sometimes back up for reasons that have nothing
  9517               to do with bidi reordering.  E.g., compositions.  The
  9518               code below is only needed when we are above the base
  9519               embedding level, so test for that explicitly.  */
  9520            && !BIDI_AT_BASE_LEVEL (it->bidi_it))
  9521     {
  9522       if (it->base_level_stop <= 0
  9523           || IT_CHARPOS (*it) < it->base_level_stop)
  9524         {
  9525           /* If we lost track of base_level_stop, we need to find
  9526              prev_stop by looking backwards.  This happens, e.g., when
  9527              we were reseated to the previous screenful of text by
  9528              vertical-motion.  */
  9529           it->base_level_stop = BEGV;
  9530           compute_stop_pos_backwards (it);
  9531           handle_stop_backwards (it, it->prev_stop);
  9532         }
  9533       else
  9534         handle_stop_backwards (it, it->base_level_stop);
  9535       it->ignore_overlay_strings_at_pos_p = false;
  9536       return GET_NEXT_DISPLAY_ELEMENT (it);
  9537     }
  9538   else
  9539     {
  9540       /* No face changes, overlays etc. in sight, so just return a
  9541          character from current_buffer.  */
  9542       unsigned char *p;
  9543       ptrdiff_t stop;
  9544 
  9545       /* We moved to the next buffer position, so any info about
  9546          previously seen overlays is no longer valid.  */
  9547       it->ignore_overlay_strings_at_pos_p = false;
  9548 
  9549       if (composition_break_at_point
  9550           && !NILP (BVAR (current_buffer, enable_multibyte_characters))
  9551           && !NILP (Vauto_composition_mode))
  9552         {
  9553           /* Limit search for composable characters to point's position.  */
  9554           if (it->bidi_it.scan_dir < 0)
  9555             stop = (PT <= IT_CHARPOS (*it)) ? PT : -1;
  9556           else
  9557             stop = (IT_CHARPOS (*it) < PT
  9558                     && PT < it->end_charpos) ? PT : it->end_charpos;
  9559         }
  9560       else
  9561         stop = it->bidi_it.scan_dir < 0 ? -1 : it->end_charpos;
  9562       if (CHAR_COMPOSED_P (it, IT_CHARPOS (*it), IT_BYTEPOS (*it),
  9563                            stop)
  9564           && next_element_from_composition (it))
  9565         {
  9566           return true;
  9567         }
  9568 
  9569       /* Get the next character, maybe multibyte.  */
  9570       p = BYTE_POS_ADDR (IT_BYTEPOS (*it));
  9571       if (it->multibyte_p && !ASCII_CHAR_P (*p))
  9572         it->c = string_char_and_length (p, &it->len);
  9573       else
  9574         it->c = *p, it->len = 1;
  9575 
  9576       /* Record what we have and where it came from.  */
  9577       it->what = IT_CHARACTER;
  9578       it->object = it->w->contents;
  9579       it->position = it->current.pos;
  9580 
  9581       /* Normally we return the character found above, except when we
  9582          really want to return an ellipsis for selective display.  */
  9583       if (it->selective)
  9584         {
  9585           if (it->c == '\n')
  9586             {
  9587               /* A value of selective > 0 means hide lines indented more
  9588                  than that number of columns.  */
  9589               if (it->selective > 0
  9590                   && IT_CHARPOS (*it) + 1 < ZV
  9591                   && indented_beyond_p (IT_CHARPOS (*it) + 1,
  9592                                         IT_BYTEPOS (*it) + 1,
  9593                                         it->selective))
  9594                 {
  9595                   success_p = next_element_from_ellipsis (it);
  9596                   it->dpvec_char_len = -1;
  9597                 }
  9598             }
  9599           else if (it->c == '\r' && it->selective == -1)
  9600             {
  9601               /* A value of selective == -1 means that everything from the
  9602                  CR to the end of the line is invisible, with maybe an
  9603                  ellipsis displayed for it.  */
  9604               success_p = next_element_from_ellipsis (it);
  9605               it->dpvec_char_len = -1;
  9606             }
  9607         }
  9608     }
  9609 
  9610   /* Value is false if end of buffer reached.  */
  9611   eassert (!success_p || it->what != IT_CHARACTER || it->len > 0);
  9612   return success_p;
  9613 }
  9614 
  9615 
  9616 /* Deliver a composition display element.  Unlike the other
  9617    next_element_from_XXX, this function is not registered in the array
  9618    get_next_element[].  It is called from next_element_from_buffer and
  9619    next_element_from_string when necessary.  */
  9620 
  9621 static bool
  9622 next_element_from_composition (struct it *it)
  9623 {
  9624   it->what = IT_COMPOSITION;
  9625   it->len = it->cmp_it.nbytes;
  9626   if (STRINGP (it->string))
  9627     {
  9628       if (it->c < 0)
  9629         {
  9630           IT_STRING_CHARPOS (*it) += it->cmp_it.nchars;
  9631           IT_STRING_BYTEPOS (*it) += it->cmp_it.nbytes;
  9632           return false;
  9633         }
  9634       it->position = it->current.string_pos;
  9635       it->object = it->string;
  9636       it->c = composition_update_it (&it->cmp_it, IT_STRING_CHARPOS (*it),
  9637                                      IT_STRING_BYTEPOS (*it), it->string);
  9638     }
  9639   else
  9640     {
  9641       if (it->c < 0)
  9642         {
  9643           IT_CHARPOS (*it) += it->cmp_it.nchars;
  9644           IT_BYTEPOS (*it) += it->cmp_it.nbytes;
  9645           if (it->bidi_p)
  9646             {
  9647               if (it->bidi_it.new_paragraph)
  9648                 bidi_paragraph_init (it->paragraph_embedding, &it->bidi_it,
  9649                                      false);
  9650               /* Resync the bidi iterator with IT's new position.
  9651                  FIXME: this doesn't support bidirectional text.  */
  9652               while (it->bidi_it.charpos < IT_CHARPOS (*it))
  9653                 bidi_move_to_visually_next (&it->bidi_it);
  9654             }
  9655           return false;
  9656         }
  9657       it->position = it->current.pos;
  9658       it->object = it->w->contents;
  9659       it->c = composition_update_it (&it->cmp_it, IT_CHARPOS (*it),
  9660                                      IT_BYTEPOS (*it), Qnil);
  9661     }
  9662   return true;
  9663 }
  9664 
  9665 
  9666 
  9667 /***********************************************************************
  9668              Moving an iterator without producing glyphs
  9669  ***********************************************************************/
  9670 
  9671 /* Check if iterator is at a position corresponding to a valid buffer
  9672    position after some move_it_ call.  */
  9673 
  9674 #define IT_POS_VALID_AFTER_MOVE_P(it)                   \
  9675   ((it)->method != GET_FROM_STRING || IT_STRING_CHARPOS (*it) == 0)
  9676 
  9677 
  9678 /* Move iterator IT to a specified buffer or X position within one
  9679    line on the display without producing glyphs.
  9680 
  9681    OP should be a bit mask including some or all of these bits:
  9682     MOVE_TO_X: Stop upon reaching x-position TO_X.
  9683     MOVE_TO_POS: Stop upon reaching buffer or string position TO_CHARPOS.
  9684    Regardless of OP's value, stop upon reaching the end of the display line.
  9685 
  9686    TO_X is normally a value 0 <= TO_X <= IT->last_visible_x.
  9687    This means, in particular, that TO_X includes window's horizontal
  9688    scroll amount.
  9689 
  9690    The return value has several possible values that
  9691    say what condition caused the scan to stop:
  9692 
  9693    MOVE_POS_MATCH_OR_ZV
  9694      - when TO_POS or ZV was reached.
  9695 
  9696    MOVE_X_REACHED
  9697      -when TO_X was reached before TO_POS or ZV were reached.
  9698 
  9699    MOVE_LINE_CONTINUED
  9700      - when we reached the end of the display area and the line must
  9701      be continued.
  9702 
  9703    MOVE_LINE_TRUNCATED
  9704      - when we reached the end of the display area and the line is
  9705      truncated.
  9706 
  9707    MOVE_NEWLINE_OR_CR
  9708      - when we stopped at a line end, i.e. a newline or a CR and selective
  9709      display is on.  */
  9710 
  9711 static enum move_it_result
  9712 move_it_in_display_line_to (struct it *it,
  9713                             ptrdiff_t to_charpos, int to_x,
  9714                             enum move_operation_enum op)
  9715 {
  9716   enum move_it_result result = MOVE_UNDEFINED;
  9717   struct glyph_row *saved_glyph_row;
  9718   struct it wrap_it, atpos_it, atx_it, ppos_it;
  9719   void *wrap_data = NULL, *atpos_data = NULL, *atx_data = NULL;
  9720   void *ppos_data = NULL;
  9721   bool may_wrap = false;
  9722   enum it_method prev_method = it->method;
  9723   ptrdiff_t closest_pos UNINIT;
  9724   ptrdiff_t prev_pos = IT_CHARPOS (*it);
  9725   bool saw_smaller_pos = prev_pos < to_charpos;
  9726   bool line_number_pending = false;
  9727 
  9728   /* Don't produce glyphs in produce_glyphs.  */
  9729   saved_glyph_row = it->glyph_row;
  9730   it->glyph_row = NULL;
  9731 
  9732   /* Use wrap_it to save a copy of IT wherever a word wrap could
  9733      occur.  Use atpos_it to save a copy of IT at the desired buffer
  9734      position, if found, so that we can scan ahead and check if the
  9735      word later overshoots the window edge.  Use atx_it similarly, for
  9736      pixel positions.  */
  9737   wrap_it.sp = -1;
  9738   atpos_it.sp = -1;
  9739   atx_it.sp = -1;
  9740 
  9741   /* Use ppos_it under bidi reordering to save a copy of IT for the
  9742      initial position.  We restore that position in IT when we have
  9743      scanned the entire display line without finding a match for
  9744      TO_CHARPOS and all the character positions are greater than
  9745      TO_CHARPOS.  We then restart the scan from the initial position,
  9746      and stop at CLOSEST_POS, which is a position > TO_CHARPOS that is
  9747      the closest to TO_CHARPOS.  */
  9748   if (it->bidi_p)
  9749     {
  9750       if ((op & MOVE_TO_POS) && IT_CHARPOS (*it) >= to_charpos)
  9751         {
  9752           SAVE_IT (ppos_it, *it, ppos_data);
  9753           closest_pos = IT_CHARPOS (*it);
  9754         }
  9755       else
  9756         closest_pos = ZV;
  9757     }
  9758 
  9759 #define BUFFER_POS_REACHED_P()                                  \
  9760   ((op & MOVE_TO_POS) != 0                                      \
  9761    && BUFFERP (it->object)                                      \
  9762    && (IT_CHARPOS (*it) == to_charpos                           \
  9763        || ((!it->bidi_p                                         \
  9764             || BIDI_AT_BASE_LEVEL (it->bidi_it))                \
  9765            && IT_CHARPOS (*it) > to_charpos)                    \
  9766        || (it->what == IT_COMPOSITION                           \
  9767            && ((IT_CHARPOS (*it) > to_charpos                   \
  9768                 && to_charpos >= it->cmp_it.charpos)            \
  9769                || (IT_CHARPOS (*it) < to_charpos                \
  9770                    && to_charpos <= it->cmp_it.charpos))))      \
  9771    && (it->method == GET_FROM_BUFFER                            \
  9772        || (it->method == GET_FROM_DISPLAY_VECTOR                \
  9773            && it->dpvec + it->current.dpvec_index + 1 >= it->dpend)))
  9774 
  9775   if (it->hpos == 0)
  9776     {
  9777       /* If line numbers are being displayed, produce a line number.
  9778          But don't do that if we are to reach first_visible_x, because
  9779          line numbers are not relevant to stuff that is not visible on
  9780          display.  */
  9781       if (!((op && MOVE_TO_X) && to_x == it->first_visible_x)
  9782           && should_produce_line_number (it))
  9783         {
  9784           if (it->current_x == it->first_visible_x)
  9785             maybe_produce_line_number (it);
  9786           else
  9787             line_number_pending = true;
  9788         }
  9789       /* If there's a line-/wrap-prefix, handle it, if we didn't already.  */
  9790       if (it->area == TEXT_AREA && !it->string_from_prefix_prop_p)
  9791         handle_line_prefix (it);
  9792     }
  9793 
  9794   if (IT_CHARPOS (*it) < CHARPOS (this_line_min_pos))
  9795     SET_TEXT_POS (this_line_min_pos, IT_CHARPOS (*it), IT_BYTEPOS (*it));
  9796 
  9797   while (true)
  9798     {
  9799       int x, i, ascent = 0, descent = 0;
  9800 
  9801 /* Utility macro to reset an iterator with x, ascent, and descent.  */
  9802 #define IT_RESET_X_ASCENT_DESCENT(IT)                   \
  9803   ((IT)->current_x = x, (IT)->max_ascent = ascent,      \
  9804    (IT)->max_descent = descent)
  9805 
  9806       /* Stop if we move beyond TO_CHARPOS (after an image or a
  9807          display string or stretch glyph).  */
  9808       if ((op & MOVE_TO_POS) != 0
  9809           && BUFFERP (it->object)
  9810           && it->method == GET_FROM_BUFFER
  9811           && (((!it->bidi_p
  9812                 /* When the iterator is at base embedding level, we
  9813                    are guaranteed that characters are delivered for
  9814                    display in strictly increasing order of their
  9815                    buffer positions.  */
  9816                 || BIDI_AT_BASE_LEVEL (it->bidi_it))
  9817                && IT_CHARPOS (*it) > to_charpos)
  9818               || (it->bidi_p
  9819                   && (prev_method == GET_FROM_IMAGE
  9820                       || prev_method == GET_FROM_STRETCH
  9821                       || prev_method == GET_FROM_STRING)
  9822                   /* Passed TO_CHARPOS from left to right.  */
  9823                   && ((prev_pos < to_charpos
  9824                        && IT_CHARPOS (*it) >= to_charpos)
  9825                       /* Passed TO_CHARPOS from right to left.  */
  9826                       || (prev_pos > to_charpos
  9827                           && IT_CHARPOS (*it) <= to_charpos)))))
  9828         {
  9829           if (it->line_wrap != WORD_WRAP || wrap_it.sp < 0)
  9830             {
  9831               result = MOVE_POS_MATCH_OR_ZV;
  9832               break;
  9833             }
  9834           else if (it->line_wrap == WORD_WRAP && atpos_it.sp < 0)
  9835             /* If wrap_it is valid, the current position might be in a
  9836                word that is wrapped.  So, save the iterator in
  9837                atpos_it and continue to see if wrapping happens.  */
  9838             SAVE_IT (atpos_it, *it, atpos_data);
  9839         }
  9840 
  9841       /* Stop when ZV reached.
  9842          We used to stop here when TO_CHARPOS reached as well, but that is
  9843          too soon if this glyph does not fit on this line.  So we handle it
  9844          explicitly below.  */
  9845       if (!get_next_display_element (it))
  9846         {
  9847           result = MOVE_POS_MATCH_OR_ZV;
  9848           break;
  9849         }
  9850 
  9851       if (it->line_wrap == TRUNCATE)
  9852         {
  9853           /* If it->pixel_width is zero, the last PRODUCE_GLYPHS call
  9854              produced something that doesn't consume any screen estate
  9855              in the text area, so we don't want to exit the loop at
  9856              TO_CHARPOS, before we produce the glyph for that buffer
  9857              position.  This happens, e.g., when there's an overlay at
  9858              TO_CHARPOS that draws a fringe bitmap.  */
  9859           if (BUFFER_POS_REACHED_P ()
  9860               && (it->pixel_width > 0
  9861                   || IT_CHARPOS (*it) > to_charpos
  9862                   || it->area != TEXT_AREA))
  9863             {
  9864               result = MOVE_POS_MATCH_OR_ZV;
  9865               break;
  9866             }
  9867         }
  9868       else
  9869         {
  9870           if (it->line_wrap == WORD_WRAP && it->area == TEXT_AREA)
  9871             {
  9872               bool next_may_wrap = may_wrap;
  9873               /* Can we wrap after this character?  */
  9874               if (char_can_wrap_after (it))
  9875                 next_may_wrap = true;
  9876               else
  9877                 next_may_wrap = false;
  9878               /* Can we wrap here? */
  9879               if (may_wrap && char_can_wrap_before (it))
  9880                 {
  9881                   /* We have reached a glyph that follows one or more
  9882                      whitespace characters or characters that allow
  9883                      wrapping after them.  If this character allows
  9884                      wrapping before it, save this position as a
  9885                      wrapping point.  */
  9886                   if (atpos_it.sp >= 0)
  9887                     {
  9888                       RESTORE_IT (it, &atpos_it, atpos_data);
  9889                       result = MOVE_POS_MATCH_OR_ZV;
  9890                       goto done;
  9891                     }
  9892                   if (atx_it.sp >= 0)
  9893                     {
  9894                       RESTORE_IT (it, &atx_it, atx_data);
  9895                       result = MOVE_X_REACHED;
  9896                       goto done;
  9897                     }
  9898                   /* Otherwise, we can wrap here.  */
  9899                   SAVE_IT (wrap_it, *it, wrap_data);
  9900                 }
  9901               /* Update may_wrap for the next iteration.  */
  9902               may_wrap = next_may_wrap;
  9903             }
  9904         }
  9905 
  9906       /* Remember the line height for the current line, in case
  9907          the next element doesn't fit on the line.  */
  9908       ascent = it->max_ascent;
  9909       descent = it->max_descent;
  9910 
  9911       /* The call to produce_glyphs will get the metrics of the
  9912          display element IT is loaded with.  Record the x-position
  9913          before this display element, in case it doesn't fit on the
  9914          line.  */
  9915       x = it->current_x;
  9916 
  9917       PRODUCE_GLYPHS (it);
  9918 
  9919       if (it->area != TEXT_AREA)
  9920         {
  9921           prev_method = it->method;
  9922           if (it->method == GET_FROM_BUFFER)
  9923             prev_pos = IT_CHARPOS (*it);
  9924           set_iterator_to_next (it, true);
  9925           if (IT_CHARPOS (*it) < CHARPOS (this_line_min_pos))
  9926             SET_TEXT_POS (this_line_min_pos,
  9927                           IT_CHARPOS (*it), IT_BYTEPOS (*it));
  9928           if (it->bidi_p
  9929               && (op & MOVE_TO_POS)
  9930               && IT_CHARPOS (*it) > to_charpos
  9931               && IT_CHARPOS (*it) < closest_pos)
  9932             closest_pos = IT_CHARPOS (*it);
  9933           continue;
  9934         }
  9935 
  9936       /* The number of glyphs we get back in IT->nglyphs will normally
  9937          be 1 except when IT->c is (i) a TAB, or (ii) a multi-glyph
  9938          character on a terminal frame, or (iii) a line end.  For the
  9939          second case, IT->nglyphs - 1 padding glyphs will be present.
  9940          (On X frames, there is only one glyph produced for a
  9941          composite character.)
  9942 
  9943          The behavior implemented below means, for continuation lines,
  9944          that as many spaces of a TAB as fit on the current line are
  9945          displayed there.  For terminal frames, as many glyphs of a
  9946          multi-glyph character are displayed in the current line, too.
  9947          This is what the old redisplay code did, and we keep it that
  9948          way.  Under X, the whole shape of a complex character must
  9949          fit on the line or it will be completely displayed in the
  9950          next line.
  9951 
  9952          Note that both for tabs and padding glyphs, all glyphs have
  9953          the same width.  */
  9954       if (it->nglyphs)
  9955         {
  9956           /* More than one glyph or glyph doesn't fit on line.  All
  9957              glyphs have the same width.  */
  9958           int single_glyph_width = it->pixel_width / it->nglyphs;
  9959           int new_x;
  9960           int x_before_this_char = x;
  9961           int hpos_before_this_char = it->hpos;
  9962 
  9963           for (i = 0; i < it->nglyphs; ++i, x = new_x)
  9964             {
  9965               new_x = x + single_glyph_width;
  9966 
  9967               /* We want to leave anything reaching TO_X to the caller.  */
  9968               if ((op & MOVE_TO_X) && new_x > to_x)
  9969                 {
  9970                   if (BUFFER_POS_REACHED_P ())
  9971                     {
  9972                       if (it->line_wrap != WORD_WRAP || wrap_it.sp < 0)
  9973                         goto buffer_pos_reached;
  9974                       if (atpos_it.sp < 0)
  9975                         {
  9976                           SAVE_IT (atpos_it, *it, atpos_data);
  9977                           IT_RESET_X_ASCENT_DESCENT (&atpos_it);
  9978                         }
  9979                     }
  9980                   else
  9981                     {
  9982                       if (it->line_wrap != WORD_WRAP || wrap_it.sp < 0)
  9983                         {
  9984                           it->current_x = x;
  9985                           result = MOVE_X_REACHED;
  9986                           break;
  9987                         }
  9988                       if (atx_it.sp < 0)
  9989                         {
  9990                           SAVE_IT (atx_it, *it, atx_data);
  9991                           IT_RESET_X_ASCENT_DESCENT (&atx_it);
  9992                         }
  9993                     }
  9994                 }
  9995 
  9996               if (/* Lines are continued.  */
  9997                   it->line_wrap != TRUNCATE
  9998                   && (/* And glyph doesn't fit on the line.  */
  9999                       new_x > it->last_visible_x
 10000                       /* Or it fits exactly and we're on a window
 10001                          system frame.  */
 10002                       || (new_x == it->last_visible_x
 10003                           && FRAME_WINDOW_P (it->f)
 10004                           && ((it->bidi_p && it->bidi_it.paragraph_dir == R2L)
 10005                               ? WINDOW_LEFT_FRINGE_WIDTH (it->w)
 10006                               : WINDOW_RIGHT_FRINGE_WIDTH (it->w)))))
 10007                 {
 10008                   bool moved_forward = false;
 10009 
 10010                   if (/* IT->hpos == 0 means the very first glyph
 10011                          doesn't fit on the line, e.g. a wide image.  */
 10012                       it->hpos == 0
 10013                       || (new_x == it->last_visible_x
 10014                           && FRAME_WINDOW_P (it->f)))
 10015                     {
 10016                       ++it->hpos;
 10017                       it->current_x = new_x;
 10018 
 10019                       /* The character's last glyph just barely fits
 10020                          in this row.  */
 10021                       if (i == it->nglyphs - 1)
 10022                         {
 10023                           /* If this is the destination position,
 10024                              return a position *before* it in this row,
 10025                              now that we know it fits in this row.  */
 10026                           if (BUFFER_POS_REACHED_P ())
 10027                             {
 10028                               bool can_wrap = true;
 10029 
 10030                               /* If the previous character says we can
 10031                                  wrap after it, but the current
 10032                                  character says we can't wrap before
 10033                                  it, then we can't wrap here.  */
 10034                               if (it->line_wrap == WORD_WRAP
 10035                                   && wrap_it.sp >= 0
 10036                                   && may_wrap
 10037                                   && IT_OVERFLOW_NEWLINE_INTO_FRINGE (it))
 10038                                 {
 10039                                   struct it tem_it;
 10040                                   void *tem_data = NULL;
 10041 
 10042                                   SAVE_IT (tem_it, *it, tem_data);
 10043                                   set_iterator_to_next (it, true);
 10044                                   if (get_next_display_element (it)
 10045                                       && !char_can_wrap_before (it))
 10046                                     can_wrap = false;
 10047                                   RESTORE_IT (it, &tem_it, tem_data);
 10048                                 }
 10049                               if (it->line_wrap != WORD_WRAP
 10050                                   || wrap_it.sp < 0
 10051                                   /* If we've just found whitespace
 10052                                      where we can wrap, effectively
 10053                                      ignore the previous wrap point --
 10054                                      it is no longer relevant, but we
 10055                                      won't have an opportunity to
 10056                                      update it, since we've reached
 10057                                      the edge of this screen line.  */
 10058                                   || (may_wrap && can_wrap
 10059                                       && IT_OVERFLOW_NEWLINE_INTO_FRINGE (it)))
 10060                                 {
 10061                                   it->hpos = hpos_before_this_char;
 10062                                   it->current_x = x_before_this_char;
 10063                                   result = MOVE_POS_MATCH_OR_ZV;
 10064                                   break;
 10065                                 }
 10066                               if (it->line_wrap == WORD_WRAP
 10067                                   && atpos_it.sp < 0)
 10068                                 {
 10069                                   SAVE_IT (atpos_it, *it, atpos_data);
 10070                                   atpos_it.current_x = x_before_this_char;
 10071                                   atpos_it.hpos = hpos_before_this_char;
 10072                                 }
 10073                             }
 10074 
 10075                           prev_method = it->method;
 10076                           if (it->method == GET_FROM_BUFFER)
 10077                             prev_pos = IT_CHARPOS (*it);
 10078                           set_iterator_to_next (it, true);
 10079                           if (IT_CHARPOS (*it) < CHARPOS (this_line_min_pos))
 10080                             SET_TEXT_POS (this_line_min_pos,
 10081                                           IT_CHARPOS (*it), IT_BYTEPOS (*it));
 10082                           /* On graphical terminals, newlines may
 10083                              "overflow" into the fringe if
 10084                              overflow-newline-into-fringe is non-nil.
 10085                              On text terminals, and on graphical
 10086                              terminals with no right margin, newlines
 10087                              may overflow into the last glyph on the
 10088                              display line.*/
 10089                           if (!FRAME_WINDOW_P (it->f)
 10090                               || ((it->bidi_p
 10091                                    && it->bidi_it.paragraph_dir == R2L)
 10092                                   ? WINDOW_LEFT_FRINGE_WIDTH (it->w)
 10093                                   : WINDOW_RIGHT_FRINGE_WIDTH (it->w)) == 0
 10094                               || IT_OVERFLOW_NEWLINE_INTO_FRINGE (it))
 10095                             {
 10096                               if (!get_next_display_element (it))
 10097                                 {
 10098                                   result = MOVE_POS_MATCH_OR_ZV;
 10099                                   break;
 10100                                 }
 10101                               moved_forward = true;
 10102                               if (BUFFER_POS_REACHED_P ())
 10103                                 {
 10104                                   if (ITERATOR_AT_END_OF_LINE_P (it))
 10105                                     result = MOVE_POS_MATCH_OR_ZV;
 10106                                   else
 10107                                     result = MOVE_LINE_CONTINUED;
 10108                                   break;
 10109                                 }
 10110                               if (ITERATOR_AT_END_OF_LINE_P (it)
 10111                                   && (it->line_wrap != WORD_WRAP
 10112                                       || wrap_it.sp < 0
 10113                                       || IT_OVERFLOW_NEWLINE_INTO_FRINGE (it)))
 10114                                 {
 10115                                   result = MOVE_NEWLINE_OR_CR;
 10116                                   break;
 10117                                 }
 10118                             }
 10119                         }
 10120                     }
 10121                   else
 10122                     IT_RESET_X_ASCENT_DESCENT (it);
 10123 
 10124                   /* If the screen line ends with whitespace (or
 10125                      wrap-able character), and we are under word-wrap,
 10126                      don't use wrap_it: it is no longer relevant, but
 10127                      we won't have an opportunity to update it, since
 10128                      we are done with this screen line.  */
 10129                   if (may_wrap && IT_OVERFLOW_NEWLINE_INTO_FRINGE (it)
 10130                       /* If the character after the one which set the
 10131                          may_wrap flag says we can't wrap before it,
 10132                          we can't wrap here.  Therefore, wrap_it
 10133                          (previously found wrap-point) _is_ relevant
 10134                          in that case.  */
 10135                       && (!moved_forward || char_can_wrap_before (it)))
 10136                     {
 10137                       /* If we've found TO_X, go back there, as we now
 10138                          know the last word fits on this screen line.  */
 10139                       if ((op & MOVE_TO_X) && new_x == it->last_visible_x
 10140                           && atx_it.sp >= 0)
 10141                         {
 10142                           RESTORE_IT (it, &atx_it, atx_data);
 10143                           atpos_it.sp = -1;
 10144                           atx_it.sp = -1;
 10145                           result = MOVE_X_REACHED;
 10146                           break;
 10147                         }
 10148                     }
 10149                   else if (wrap_it.sp >= 0)
 10150                     {
 10151                       RESTORE_IT (it, &wrap_it, wrap_data);
 10152                       atpos_it.sp = -1;
 10153                       atx_it.sp = -1;
 10154                     }
 10155 
 10156                   move_trace ("move_it_in: continued at %td\n",
 10157                               IT_CHARPOS (*it));
 10158                   result = MOVE_LINE_CONTINUED;
 10159                   break;
 10160                 }
 10161 
 10162               if (BUFFER_POS_REACHED_P ())
 10163                 {
 10164                   if (it->line_wrap != WORD_WRAP || wrap_it.sp < 0)
 10165                     goto buffer_pos_reached;
 10166                   if (it->line_wrap == WORD_WRAP && atpos_it.sp < 0)
 10167                     {
 10168                       SAVE_IT (atpos_it, *it, atpos_data);
 10169                       IT_RESET_X_ASCENT_DESCENT (&atpos_it);
 10170                     }
 10171                 }
 10172 
 10173               if (new_x > it->first_visible_x)
 10174                 {
 10175                   /* If we have reached the visible portion of the
 10176                      screen line, produce the line number if needed.  */
 10177                   if (line_number_pending)
 10178                     {
 10179                       line_number_pending = false;
 10180                       it->current_x = it->first_visible_x;
 10181                       maybe_produce_line_number (it);
 10182                       it->current_x += new_x - it->first_visible_x;
 10183                     }
 10184                   /* Glyph is visible.  Increment number of glyphs that
 10185                      would be displayed.  */
 10186                   ++it->hpos;
 10187                 }
 10188             }
 10189 
 10190           if (result != MOVE_UNDEFINED)
 10191             break;
 10192         }
 10193       else if (BUFFER_POS_REACHED_P ())
 10194         {
 10195         buffer_pos_reached:
 10196           IT_RESET_X_ASCENT_DESCENT (it);
 10197           result = MOVE_POS_MATCH_OR_ZV;
 10198           break;
 10199         }
 10200       else if ((op & MOVE_TO_X) && it->current_x >= to_x)
 10201         {
 10202           /* Stop when TO_X specified and reached.  This check is
 10203              necessary here because of lines consisting of a line end,
 10204              only.  The line end will not produce any glyphs and we
 10205              would never get MOVE_X_REACHED.  */
 10206           eassert (it->nglyphs == 0);
 10207           result = MOVE_X_REACHED;
 10208           break;
 10209         }
 10210 
 10211       /* Is this a line end?  If yes, we're done.  */
 10212       if (ITERATOR_AT_END_OF_LINE_P (it))
 10213         {
 10214           /* If we are past TO_CHARPOS, but never saw any character
 10215              positions smaller than TO_CHARPOS, return
 10216              MOVE_POS_MATCH_OR_ZV, like the unidirectional display
 10217              did.  */
 10218           if (it->bidi_p && (op & MOVE_TO_POS) != 0)
 10219             {
 10220               if (!saw_smaller_pos && IT_CHARPOS (*it) > to_charpos)
 10221                 {
 10222                   if (closest_pos < ZV)
 10223                     {
 10224                       RESTORE_IT (it, &ppos_it, ppos_data);
 10225                       /* Don't recurse if closest_pos is equal to
 10226                          to_charpos, since we have just tried that.  */
 10227                       if (closest_pos != to_charpos)
 10228                         move_it_in_display_line_to (it, closest_pos, -1,
 10229                                                     MOVE_TO_POS);
 10230                       result = MOVE_POS_MATCH_OR_ZV;
 10231                     }
 10232                   else
 10233                     goto buffer_pos_reached;
 10234                 }
 10235               else if (it->line_wrap == WORD_WRAP && atpos_it.sp >= 0
 10236                        && IT_CHARPOS (*it) > to_charpos)
 10237                 goto buffer_pos_reached;
 10238               else
 10239                 result = MOVE_NEWLINE_OR_CR;
 10240             }
 10241           else
 10242             result = MOVE_NEWLINE_OR_CR;
 10243           /* If lines are truncated, and the line we moved across is
 10244              completely hscrolled out of view, reset the line metrics
 10245              to those of the newline we've just processed, so that
 10246              glyphs not on display don't affect the line's height.  */
 10247           if (it->line_wrap == TRUNCATE
 10248               && it->current_x <= it->first_visible_x
 10249               && result == MOVE_NEWLINE_OR_CR
 10250               && it->char_to_display == '\n')
 10251             {
 10252               it->max_ascent = it->ascent;
 10253               it->max_descent = it->descent;
 10254             }
 10255           /* If we've processed the newline, make sure this flag is
 10256              reset, as it must only be set when the newline itself is
 10257              processed.  */
 10258           if (result == MOVE_NEWLINE_OR_CR)
 10259             it->constrain_row_ascent_descent_p = false;
 10260           break;
 10261         }
 10262 
 10263       prev_method = it->method;
 10264       if (it->method == GET_FROM_BUFFER)
 10265         prev_pos = IT_CHARPOS (*it);
 10266 
 10267       /* Detect overly-wide wrap-prefixes made of (space ...) display
 10268          properties.  When such a wrap prefix reaches past the right
 10269          margin of the window, we need to avoid the call to
 10270          set_iterator_to_next below, so that it->line_wrap is left at
 10271          its TRUNCATE value wisely set by handle_line_prefix.
 10272          Otherwise, set_iterator_to_next will pop the iterator stack,
 10273          restore it->line_wrap, and we might miss the opportunity to
 10274          exit the loop and return.  */
 10275       bool overwide_wrap_prefix =
 10276         CONSP (it->object) && EQ (XCAR (it->object), Qspace)
 10277         && it->sp > 0 && it->method == GET_FROM_STRETCH
 10278         && it->current_x >= it->last_visible_x
 10279         && it->continuation_lines_width > 0
 10280         && it->line_wrap == TRUNCATE && it->stack[0].line_wrap != TRUNCATE;
 10281       /* The current display element has been consumed.  Advance
 10282          to the next.  */
 10283       if (!overwide_wrap_prefix)
 10284         set_iterator_to_next (it, true);
 10285       if (IT_CHARPOS (*it) < CHARPOS (this_line_min_pos))
 10286         SET_TEXT_POS (this_line_min_pos, IT_CHARPOS (*it), IT_BYTEPOS (*it));
 10287       if (IT_CHARPOS (*it) < to_charpos)
 10288         saw_smaller_pos = true;
 10289       if (it->bidi_p
 10290           && (op & MOVE_TO_POS)
 10291           && IT_CHARPOS (*it) >= to_charpos
 10292           && IT_CHARPOS (*it) < closest_pos)
 10293         closest_pos = IT_CHARPOS (*it);
 10294 
 10295       /* Stop if lines are truncated and IT's current x-position is
 10296          past the right edge of the window now.  */
 10297       if (it->line_wrap == TRUNCATE
 10298           && it->current_x >= it->last_visible_x)
 10299         {
 10300           if (!FRAME_WINDOW_P (it->f)
 10301               || ((it->bidi_p && it->bidi_it.paragraph_dir == R2L)
 10302                   ? WINDOW_LEFT_FRINGE_WIDTH (it->w)
 10303                   : WINDOW_RIGHT_FRINGE_WIDTH (it->w)) == 0
 10304               || IT_OVERFLOW_NEWLINE_INTO_FRINGE (it))
 10305             {
 10306               bool at_eob_p = false;
 10307 
 10308               if ((at_eob_p = !get_next_display_element (it))
 10309                   || BUFFER_POS_REACHED_P ()
 10310                   /* If we are past TO_CHARPOS, but never saw any
 10311                      character positions smaller than TO_CHARPOS,
 10312                      return MOVE_POS_MATCH_OR_ZV, like the
 10313                      unidirectional display did.  */
 10314                   || (it->bidi_p && (op & MOVE_TO_POS) != 0
 10315                       && !saw_smaller_pos
 10316                       && IT_CHARPOS (*it) > to_charpos))
 10317                 {
 10318                   if (it->bidi_p
 10319                       && !BUFFER_POS_REACHED_P ()
 10320                       && !at_eob_p && closest_pos < ZV)
 10321                     {
 10322                       RESTORE_IT (it, &ppos_it, ppos_data);
 10323                       if (closest_pos != to_charpos)
 10324                         move_it_in_display_line_to (it, closest_pos, -1,
 10325                                                     MOVE_TO_POS);
 10326                     }
 10327                   result = MOVE_POS_MATCH_OR_ZV;
 10328                   break;
 10329                 }
 10330               if (ITERATOR_AT_END_OF_LINE_P (it))
 10331                 {
 10332                   result = MOVE_NEWLINE_OR_CR;
 10333                   break;
 10334                 }
 10335             }
 10336           else if (it->bidi_p && (op & MOVE_TO_POS) != 0
 10337                    && !saw_smaller_pos
 10338                    && IT_CHARPOS (*it) > to_charpos)
 10339             {
 10340               if (closest_pos < ZV)
 10341                 {
 10342                   RESTORE_IT (it, &ppos_it, ppos_data);
 10343                   if (closest_pos != to_charpos)
 10344                     move_it_in_display_line_to (it, closest_pos, -1,
 10345                                                 MOVE_TO_POS);
 10346                 }
 10347               result = MOVE_POS_MATCH_OR_ZV;
 10348               break;
 10349             }
 10350           result = MOVE_LINE_TRUNCATED;
 10351           break;
 10352         }
 10353 #undef IT_RESET_X_ASCENT_DESCENT
 10354     }
 10355 
 10356 #undef BUFFER_POS_REACHED_P
 10357 
 10358   /* If we scanned beyond TO_POS, restore the saved iterator either to
 10359      the wrap point (if found), or to atpos/atx location.  We decide which
 10360      data to use to restore the saved iterator state by their X coordinates,
 10361      since buffer positions might increase non-monotonically with screen
 10362      coordinates due to bidi reordering.  */
 10363   if (result == MOVE_LINE_CONTINUED
 10364       && it->line_wrap == WORD_WRAP
 10365       && wrap_it.sp >= 0
 10366       && ((atpos_it.sp >= 0 && wrap_it.current_x < atpos_it.current_x)
 10367           || (atx_it.sp >= 0 && wrap_it.current_x < atx_it.current_x)))
 10368     RESTORE_IT (it, &wrap_it, wrap_data);
 10369   else if (atpos_it.sp >= 0)
 10370     RESTORE_IT (it, &atpos_it, atpos_data);
 10371   else if (atx_it.sp >= 0)
 10372     RESTORE_IT (it, &atx_it, atx_data);
 10373 
 10374  done:
 10375 
 10376   if (atpos_data)
 10377     bidi_unshelve_cache (atpos_data, true);
 10378   if (atx_data)
 10379     bidi_unshelve_cache (atx_data, true);
 10380   if (wrap_data)
 10381     bidi_unshelve_cache (wrap_data, true);
 10382   if (ppos_data)
 10383     bidi_unshelve_cache (ppos_data, true);
 10384 
 10385   /* Restore the iterator settings altered at the beginning of this
 10386      function.  */
 10387   it->glyph_row = saved_glyph_row;
 10388   return result;
 10389 }
 10390 
 10391 /* For external use.  */
 10392 void
 10393 move_it_in_display_line (struct it *it,
 10394                          ptrdiff_t to_charpos, int to_x,
 10395                          enum move_operation_enum op)
 10396 {
 10397   if (it->line_wrap == WORD_WRAP
 10398       && (op & MOVE_TO_X))
 10399     {
 10400       struct it save_it;
 10401       void *save_data = NULL;
 10402       int skip;
 10403 
 10404       SAVE_IT (save_it, *it, save_data);
 10405       skip = move_it_in_display_line_to (it, to_charpos, to_x, op);
 10406       /* When word-wrap is on, TO_X may lie past the end
 10407          of a wrapped line.  Then it->current is the
 10408          character on the next line, so backtrack to the
 10409          space before the wrap point.  */
 10410       if (skip == MOVE_LINE_CONTINUED)
 10411         {
 10412           int prev_x = max (it->current_x - 1, 0);
 10413           RESTORE_IT (it, &save_it, save_data);
 10414           move_it_in_display_line_to
 10415             (it, -1, prev_x, MOVE_TO_X);
 10416         }
 10417       else
 10418         bidi_unshelve_cache (save_data, true);
 10419     }
 10420   else
 10421     move_it_in_display_line_to (it, to_charpos, to_x, op);
 10422 }
 10423 
 10424 
 10425 /* Move IT forward until it satisfies one or more of the criteria in
 10426    TO_CHARPOS, TO_X, TO_Y, and TO_VPOS.
 10427 
 10428    OP is a bit-mask that specifies where to stop, and in particular,
 10429    which of those four position arguments makes a difference.  See the
 10430    description of enum move_operation_enum.
 10431 
 10432    If TO_CHARPOS is in invisible text, e.g. a truncated part of a
 10433    screen line, this function will set IT to the next position that is
 10434    displayed to the right of TO_CHARPOS on the screen.
 10435 
 10436    Return the maximum pixel length of any line scanned but never more
 10437    than it.last_visible_x.  */
 10438 
 10439 int
 10440 move_it_to (struct it *it, ptrdiff_t to_charpos, int to_x, int to_y, int to_vpos, int op)
 10441 {
 10442   enum move_it_result skip, skip2 = MOVE_X_REACHED;
 10443   int line_height, line_start_x = 0, reached = 0;
 10444   int max_current_x = 0;
 10445   void *backup_data = NULL;
 10446   ptrdiff_t orig_charpos = -1;
 10447   enum it_method orig_method = NUM_IT_METHODS;
 10448 
 10449   for (;;)
 10450     {
 10451       orig_charpos = IT_CHARPOS (*it);
 10452       orig_method = it->method;
 10453       if (op & MOVE_TO_VPOS)
 10454         {
 10455           /* If no TO_CHARPOS and no TO_X specified, stop at the
 10456              start of the line TO_VPOS.  */
 10457           if ((op & (MOVE_TO_X | MOVE_TO_POS)) == 0)
 10458             {
 10459               if (it->vpos == to_vpos)
 10460                 {
 10461                   reached = 1;
 10462                   break;
 10463                 }
 10464               else
 10465                 skip = move_it_in_display_line_to (it, -1, -1, 0);
 10466             }
 10467           else
 10468             {
 10469               /* TO_VPOS >= 0 means stop at TO_X in the line at
 10470                  TO_VPOS, or at TO_POS, whichever comes first.  */
 10471               if (it->vpos == to_vpos)
 10472                 {
 10473                   reached = 2;
 10474                   break;
 10475                 }
 10476 
 10477               skip = move_it_in_display_line_to (it, to_charpos, to_x, op);
 10478 
 10479               if (skip == MOVE_POS_MATCH_OR_ZV || it->vpos == to_vpos)
 10480                 {
 10481                   reached = 3;
 10482                   break;
 10483                 }
 10484               else if (skip == MOVE_X_REACHED && it->vpos != to_vpos)
 10485                 {
 10486                   /* We have reached TO_X but not in the line we want.  */
 10487                   skip = move_it_in_display_line_to (it, to_charpos,
 10488                                                      -1, MOVE_TO_POS);
 10489                   if (skip == MOVE_POS_MATCH_OR_ZV)
 10490                     {
 10491                       reached = 4;
 10492                       break;
 10493                     }
 10494                 }
 10495             }
 10496         }
 10497       else if (op & MOVE_TO_Y)
 10498         {
 10499           struct it it_backup;
 10500 
 10501           if (it->line_wrap == WORD_WRAP)
 10502             SAVE_IT (it_backup, *it, backup_data);
 10503 
 10504           /* TO_Y specified means stop at TO_X in the line containing
 10505              TO_Y---or at TO_CHARPOS if this is reached first.  The
 10506              problem is that we can't really tell whether the line
 10507              contains TO_Y before we have completely scanned it, and
 10508              this may skip past TO_X.  What we do is to first scan to
 10509              TO_X.
 10510 
 10511              If TO_X is not specified, use a TO_X of zero.  The reason
 10512              is to make the outcome of this function more predictable.
 10513              If we didn't use TO_X == 0, we would stop at the end of
 10514              the line which is probably not what a caller would expect
 10515              to happen.  */
 10516           skip = move_it_in_display_line_to
 10517             (it, to_charpos, ((op & MOVE_TO_X) ? to_x : 0),
 10518              (MOVE_TO_X | (op & MOVE_TO_POS)));
 10519 
 10520           /* If TO_CHARPOS is reached or ZV, we don't have to do more.  */
 10521           if (skip == MOVE_POS_MATCH_OR_ZV)
 10522             reached = 5;
 10523           else if (skip == MOVE_X_REACHED)
 10524             {
 10525               /* If TO_X was reached, we want to know whether TO_Y is
 10526                  in the line.  We know this is the case if the already
 10527                  scanned glyphs make the line tall enough.  Otherwise,
 10528                  we must check by scanning the rest of the line.  */
 10529               line_height = it->max_ascent + it->max_descent;
 10530               if (to_y >= it->current_y
 10531                   && to_y < it->current_y + line_height)
 10532                 {
 10533                   reached = 6;
 10534                   break;
 10535                 }
 10536               SAVE_IT (it_backup, *it, backup_data);
 10537               move_trace ("move_it: from %td\n", IT_CHARPOS (*it));
 10538               skip2 = move_it_in_display_line_to (it, to_charpos, -1,
 10539                                                   op & MOVE_TO_POS);
 10540               move_trace ("move_it: to %td\n", IT_CHARPOS (*it));
 10541               line_height = it->max_ascent + it->max_descent;
 10542               move_trace ("move_it: line_height = %d\n", line_height);
 10543 
 10544               if (to_y >= it->current_y
 10545                   && to_y < it->current_y + line_height)
 10546                 {
 10547                   /* If TO_Y is in this line and TO_X was reached
 10548                      above, we scanned too far.  We have to restore
 10549                      IT's settings to the ones before skipping.  But
 10550                      keep the more accurate values of max_ascent and
 10551                      max_descent we've found while skipping the rest
 10552                      of the line, for the sake of callers, such as
 10553                      pos_visible_p, that need to know the line
 10554                      height.  */
 10555                   int max_ascent = it->max_ascent;
 10556                   int max_descent = it->max_descent;
 10557 
 10558                   RESTORE_IT (it, &it_backup, backup_data);
 10559                   it->max_ascent = max_ascent;
 10560                   it->max_descent = max_descent;
 10561                   reached = 6;
 10562                 }
 10563               else
 10564                 {
 10565                   skip = skip2;
 10566                   if (skip == MOVE_POS_MATCH_OR_ZV)
 10567                     {
 10568                       reached = 7;
 10569                       /* If the last move_it_in_display_line_to call
 10570                          took us away from TO_CHARPOS, back up to the
 10571                          previous position, as it is a better
 10572                          approximation of TO_CHARPOS.  (Note that we
 10573                          could have both positions after TO_CHARPOS or
 10574                          both positions before it, due to bidi
 10575                          reordering.)  */
 10576                       if (to_charpos > 0
 10577                           && IT_CHARPOS (*it) != to_charpos
 10578                           && ((IT_CHARPOS (it_backup) > to_charpos)
 10579                               == (IT_CHARPOS (*it) > to_charpos)))
 10580                         {
 10581                           int max_ascent = it->max_ascent;
 10582                           int max_descent = it->max_descent;
 10583 
 10584                           RESTORE_IT (it, &it_backup, backup_data);
 10585                           it->max_ascent = max_ascent;
 10586                           it->max_descent = max_descent;
 10587                         }
 10588                     }
 10589                 }
 10590             }
 10591           else
 10592             {
 10593               /* Check whether TO_Y is in this line.  */
 10594               line_height = it->max_ascent + it->max_descent;
 10595               move_trace ("move_it: line_height = %d\n", line_height);
 10596 
 10597               if (to_y >= it->current_y
 10598                   && to_y < it->current_y + line_height)
 10599                 {
 10600                   if (to_y > it->current_y)
 10601                     max_current_x = max (it->current_x, max_current_x);
 10602 
 10603                   /* When word-wrap is on, TO_X may lie past the end
 10604                      of a wrapped line.  Then it->current is the
 10605                      character on the next line, so backtrack to the
 10606                      space before the wrap point.  */
 10607                   if (skip == MOVE_LINE_CONTINUED
 10608                       && it->line_wrap == WORD_WRAP)
 10609                     {
 10610                       int prev_x = max (it->current_x - 1, 0);
 10611                       RESTORE_IT (it, &it_backup, backup_data);
 10612                       skip = move_it_in_display_line_to
 10613                         (it, -1, prev_x, MOVE_TO_X);
 10614                     }
 10615 
 10616                   reached = 6;
 10617                 }
 10618             }
 10619 
 10620           if (reached)
 10621             {
 10622               max_current_x = max (it->current_x, max_current_x);
 10623               break;
 10624             }
 10625         }
 10626       else if (BUFFERP (it->object)
 10627                && (it->method == GET_FROM_BUFFER
 10628                    || it->method == GET_FROM_STRETCH)
 10629                && IT_CHARPOS (*it) >= to_charpos
 10630                /* Under bidi iteration, a call to set_iterator_to_next
 10631                   can scan far beyond to_charpos if the initial
 10632                   portion of the next line needs to be reordered.  In
 10633                   that case, give move_it_in_display_line_to another
 10634                   chance below.  */
 10635                && !(it->bidi_p
 10636                     && it->bidi_it.scan_dir == -1))
 10637         skip = MOVE_POS_MATCH_OR_ZV;
 10638       else
 10639         skip = move_it_in_display_line_to (it, to_charpos, -1, MOVE_TO_POS);
 10640 
 10641       switch (skip)
 10642         {
 10643         case MOVE_POS_MATCH_OR_ZV:
 10644           max_current_x = max (it->current_x, max_current_x);
 10645           reached = 8;
 10646           goto out;
 10647 
 10648         case MOVE_NEWLINE_OR_CR:
 10649           max_current_x = max (it->current_x, max_current_x);
 10650           if (!IT_OVERFLOW_NEWLINE_INTO_FRINGE (it))
 10651             it->override_ascent = -1;
 10652           set_iterator_to_next (it, true);
 10653           it->continuation_lines_width = 0;
 10654           break;
 10655 
 10656         case MOVE_LINE_TRUNCATED:
 10657           max_current_x = it->last_visible_x;
 10658           it->continuation_lines_width = 0;
 10659           reseat_at_next_visible_line_start (it, false);
 10660           if ((op & MOVE_TO_POS) != 0
 10661               && (IT_CHARPOS (*it) > to_charpos
 10662                   || (IT_CHARPOS (*it) == to_charpos
 10663                       /* Consider TO_CHARPOS as REACHED if we are at
 10664                          EOB that ends in something other than a newline.  */
 10665                       && to_charpos == ZV
 10666                       && (ZV_BYTE <= 1 || FETCH_BYTE (ZV_BYTE - 1) != '\n')
 10667                       /* But if we have a display or an overlay string
 10668                          at EOB, keep going until we exhaust all the
 10669                          characters of the string(s).  */
 10670                       && (it->sp == 0
 10671                           || (STRINGP (it->string)
 10672                               && (it->current.overlay_string_index < 0
 10673                                   || (it->current.overlay_string_index >= 0
 10674                                       && it->current.overlay_string_index
 10675                                          >= it->n_overlay_strings - 1))
 10676                               && IT_STRING_CHARPOS (*it) >= it->end_charpos)))))
 10677             {
 10678               reached = 9;
 10679               goto out;
 10680             }
 10681           break;
 10682 
 10683         case MOVE_LINE_CONTINUED:
 10684           max_current_x = it->last_visible_x;
 10685           /* For continued lines ending in a tab, some of the glyphs
 10686              associated with the tab are displayed on the current
 10687              line.  Since it->current_x does not include these glyphs,
 10688              we use it->last_visible_x instead.  */
 10689           if (it->c == '\t')
 10690             {
 10691               it->continuation_lines_width += it->last_visible_x;
 10692               /* When moving by vpos, ensure that the iterator really
 10693                  advances to the next line (bug#847, bug#969).  Fixme:
 10694                  do we need to do this in other circumstances?  */
 10695               if (it->current_x != it->last_visible_x
 10696                   && (op & MOVE_TO_VPOS)
 10697                   && !(op & (MOVE_TO_X | MOVE_TO_POS)))
 10698                 {
 10699                   line_start_x = it->current_x + it->pixel_width
 10700                     - it->last_visible_x;
 10701                   if (FRAME_WINDOW_P (it->f))
 10702                     {
 10703                       struct face *face = FACE_FROM_ID (it->f, it->face_id);
 10704                       struct font *face_font = face->font;
 10705 
 10706                       /* When display_line produces a continued line
 10707                          that ends in a TAB, it skips a tab stop that
 10708                          is closer than the font's space character
 10709                          width (see gui_produce_glyphs where it produces
 10710                          the stretch glyph which represents a TAB).
 10711                          We need to reproduce the same logic here.  */
 10712                       eassert (face_font);
 10713                       if (face_font)
 10714                         {
 10715                           if (line_start_x < face_font->space_width)
 10716                             line_start_x
 10717                               += it->tab_width * face_font->space_width;
 10718                         }
 10719                     }
 10720                   set_iterator_to_next (it, false);
 10721                 }
 10722             }
 10723           else
 10724             {
 10725               /* Make sure we do advance, otherwise we might infloop.
 10726                  This could happen when the first display element is
 10727                  wider than the window, or if we have a wrap-prefix
 10728                  that doesn't leave enough space after it to display
 10729                  even a single character.  We only do this for moving
 10730                  through buffer text, as with display/overlay strings
 10731                  we'd need to also compare it->object's, and this is
 10732                  unlikely to happen in that case anyway.  */
 10733               if (IT_CHARPOS (*it) == orig_charpos
 10734                   && it->method == orig_method
 10735                   && orig_method == GET_FROM_BUFFER)
 10736                 set_iterator_to_next (it, false);
 10737               it->continuation_lines_width += it->current_x;
 10738             }
 10739           break;
 10740 
 10741         default:
 10742           emacs_abort ();
 10743         }
 10744 
 10745       /* Reset/increment for the next run.  */
 10746       it->current_x = line_start_x;
 10747       line_start_x = 0;
 10748       it->hpos = 0;
 10749       it->line_number_produced_p = false;
 10750       it->current_y += it->max_ascent + it->max_descent;
 10751       ++it->vpos;
 10752       last_height = it->max_ascent + it->max_descent;
 10753       it->max_ascent = it->max_descent = 0;
 10754     }
 10755 
 10756  out:
 10757 
 10758   /* On text terminals, we may stop at the end of a line in the middle
 10759      of a multi-character glyph.  If the glyph itself is continued,
 10760      i.e. it is actually displayed on the next line, don't treat this
 10761      stopping point as valid; move to the next line instead (unless
 10762      that brings us offscreen).  */
 10763   if (!FRAME_WINDOW_P (it->f)
 10764       && op & MOVE_TO_POS
 10765       && IT_CHARPOS (*it) == to_charpos
 10766       && it->what == IT_CHARACTER
 10767       && it->nglyphs > 1
 10768       && it->line_wrap == WINDOW_WRAP
 10769       && it->current_x == it->last_visible_x - 1
 10770       && it->c != '\n'
 10771       && it->c != '\t'
 10772       && it->w->window_end_valid
 10773       && it->vpos < it->w->window_end_vpos)
 10774     {
 10775       it->continuation_lines_width += it->current_x;
 10776       it->current_x = it->hpos = it->max_ascent = it->max_descent = 0;
 10777       it->current_y += it->max_ascent + it->max_descent;
 10778       ++it->vpos;
 10779       last_height = it->max_ascent + it->max_descent;
 10780     }
 10781 
 10782   if (backup_data)
 10783     bidi_unshelve_cache (backup_data, true);
 10784 
 10785   move_trace ("move_it_to: reached %d\n", reached);
 10786 
 10787   return max_current_x;
 10788 }
 10789 
 10790 
 10791 /* Move iterator IT backward by a specified y-distance DY, DY >= 0.
 10792 
 10793    If DY > 0, move IT backward that many pixels.
 10794    DY = 0 means move IT backward to the preceding line start or to BEGV.
 10795    This function may move over less or more than DY pixels if
 10796    IT->current_y - DY ends up in the middle of a line; in this case
 10797    IT->current_y will be set to the top of the line either before or
 10798    after the exact pixel coordinate.  */
 10799 
 10800 void
 10801 move_it_vertically_backward (struct it *it, int dy)
 10802 {
 10803   int nlines, h;
 10804   struct it it2, it3;
 10805   void *it2data = NULL, *it3data = NULL;
 10806   ptrdiff_t start_pos;
 10807   int nchars_per_row
 10808     = (it->last_visible_x - it->first_visible_x) / FRAME_COLUMN_WIDTH (it->f);
 10809   ptrdiff_t pos_limit;
 10810 
 10811  move_further_back:
 10812   eassert (dy >= 0);
 10813 
 10814   start_pos = IT_CHARPOS (*it);
 10815 
 10816   /* Estimate how many newlines we must move back.  */
 10817   nlines = max (1, dy / default_line_pixel_height (it->w));
 10818   if (it->line_wrap == TRUNCATE || nchars_per_row == 0)
 10819     pos_limit = BEGV;
 10820   else
 10821     pos_limit = max (start_pos - nlines * nchars_per_row, BEGV);
 10822 
 10823   /* Set the iterator's position that many lines back.  But don't go
 10824      back more than NLINES full screen lines -- this wins a day with
 10825      buffers which have very long lines.  */
 10826   while (nlines-- && IT_CHARPOS (*it) > pos_limit)
 10827     back_to_previous_visible_line_start (it);
 10828 
 10829   /* Reseat the iterator here.  When moving backward, we don't want
 10830      reseat to skip forward over invisible text, set up the iterator
 10831      to deliver from overlay strings at the new position etc.  So,
 10832      use reseat_1 here.  */
 10833   reseat_1 (it, it->current.pos, true);
 10834 
 10835   /* We are now surely at a line start.  */
 10836   it->current_x = it->hpos = 0; /* FIXME: this is incorrect when bidi
 10837                                    reordering is in effect.  */
 10838   it->continuation_lines_width = 0;
 10839 
 10840   /* Move forward and see what y-distance we moved.  First move to the
 10841      start of the next line so that we get its height.  We need this
 10842      height to be able to tell whether we reached the specified
 10843      y-distance.  */
 10844   SAVE_IT (it2, *it, it2data);
 10845   it2.max_ascent = it2.max_descent = 0;
 10846   do
 10847     {
 10848       move_it_to (&it2, start_pos, -1, -1, it2.vpos + 1,
 10849                   MOVE_TO_POS | MOVE_TO_VPOS);
 10850     }
 10851   while (!(IT_POS_VALID_AFTER_MOVE_P (&it2)
 10852            /* If we are in a display string which starts at START_POS,
 10853               and that display string includes a newline, and we are
 10854               right after that newline (i.e. at the beginning of a
 10855               display line), exit the loop, because otherwise we will
 10856               infloop, since move_it_to will see that it is already at
 10857               START_POS and will not move.  */
 10858            || (it2.method == GET_FROM_STRING
 10859                && IT_CHARPOS (it2) == start_pos
 10860                && SREF (it2.string, IT_STRING_BYTEPOS (it2) - 1) == '\n')));
 10861   eassert (IT_CHARPOS (*it) >= BEGV);
 10862   SAVE_IT (it3, it2, it3data);
 10863 
 10864   move_it_to (&it2, start_pos, -1, -1, -1, MOVE_TO_POS);
 10865   eassert (IT_CHARPOS (*it) >= BEGV);
 10866   /* H is the actual vertical distance from the position in *IT
 10867      and the starting position.  */
 10868   h = it2.current_y - it->current_y;
 10869   /* NLINES is the distance in number of lines.  */
 10870   nlines = it2.vpos - it->vpos;
 10871 
 10872   /* Correct IT's y and vpos position
 10873      so that they are relative to the starting point.  */
 10874   it->vpos -= nlines;
 10875   it->current_y -= h;
 10876 
 10877   if (dy == 0)
 10878     {
 10879       /* DY == 0 means move to the start of the screen line.  The
 10880          value of nlines is > 0 if continuation lines were involved,
 10881          or if the original IT position was at start of a line.  */
 10882       RESTORE_IT (it, it, it2data);
 10883       if (nlines > 0)
 10884         move_it_by_lines (it, nlines);
 10885       /* The above code moves us to some position NLINES down,
 10886          usually to its first glyph (leftmost in an L2R line), but
 10887          that's not necessarily the start of the line, under bidi
 10888          reordering.  We want to get to the character position
 10889          that is immediately after the newline of the previous
 10890          line.  */
 10891       if (it->bidi_p
 10892           && !it->continuation_lines_width
 10893           && !STRINGP (it->string)
 10894           && IT_CHARPOS (*it) > BEGV
 10895           && FETCH_BYTE (IT_BYTEPOS (*it) - 1) != '\n')
 10896         {
 10897           ptrdiff_t cp = IT_CHARPOS (*it), bp = IT_BYTEPOS (*it);
 10898 
 10899           dec_both (&cp, &bp);
 10900           SET_WITH_NARROWED_BEGV (it, cp,
 10901                                   find_newline_no_quit (cp, bp, -1, NULL),
 10902                                   get_small_narrowing_begv (it->w, IT_CHARPOS (*it)));
 10903           move_it_to (it, cp, -1, -1, -1, MOVE_TO_POS);
 10904         }
 10905       bidi_unshelve_cache (it3data, true);
 10906     }
 10907   else
 10908     {
 10909       /* The y-position we try to reach, relative to *IT.
 10910          Note that H has been subtracted in front of the if-statement.  */
 10911       int target_y = it->current_y + h - dy;
 10912       int y0 = it3.current_y;
 10913       int y1;
 10914       int line_height;
 10915 
 10916       RESTORE_IT (&it3, &it3, it3data);
 10917       y1 = line_bottom_y (&it3);
 10918       line_height = y1 - y0;
 10919       RESTORE_IT (it, it, it2data);
 10920       /* If we did not reach target_y, try to move further backward if
 10921          we can.  If we moved too far backward, try to move forward.  */
 10922       if (target_y < it->current_y
 10923           /* This is heuristic.  In a window that's 3 lines high, with
 10924              a line height of 13 pixels each, recentering with point
 10925              on the bottom line will try to move -39/2 = 19 pixels
 10926              backward.  Try to avoid moving into the first line.  */
 10927           && (it->current_y - target_y
 10928               > min (window_box_height (it->w), line_height * 2 / 3))
 10929           && IT_CHARPOS (*it) > BEGV)
 10930         {
 10931           move_trace ("  not far enough -> move_vert %d\n",
 10932                       target_y - it->current_y);
 10933           dy = it->current_y - target_y;
 10934           goto move_further_back;
 10935         }
 10936       else if (target_y >= it->current_y + line_height
 10937                && IT_CHARPOS (*it) < ZV)
 10938         {
 10939           /* Should move forward by at least one line, maybe more.
 10940 
 10941              Note: Calling move_it_by_lines can be expensive on
 10942              terminal frames, where compute_motion is used (via
 10943              vmotion) to do the job, when there are very long lines
 10944              and truncate-lines is nil.  That's the reason for
 10945              treating terminal frames specially here.  */
 10946 
 10947           if (!FRAME_WINDOW_P (it->f))
 10948             move_it_vertically (it, target_y - it->current_y);
 10949           else
 10950             {
 10951               struct text_pos last_pos;
 10952               int last_y, last_vpos;
 10953               do
 10954                 {
 10955                   last_pos = it->current.pos;
 10956                   last_y = it->current_y;
 10957                   last_vpos = it->vpos;
 10958                   move_it_by_lines (it, 1);
 10959                 }
 10960               while (target_y > it->current_y && IT_CHARPOS (*it) < ZV);
 10961               if (it->current_y > target_y)
 10962                 {
 10963                   reseat (it, last_pos, true);
 10964                   it->current_y = last_y;
 10965                   it->vpos = last_vpos;
 10966                 }
 10967             }
 10968         }
 10969     }
 10970 }
 10971 
 10972 
 10973 /* Move IT by a specified amount of pixel lines DY.  DY negative means
 10974    move backwards.  DY = 0 means move to start of screen line.  At the
 10975    end, IT will be on the start of a screen line.  */
 10976 
 10977 void
 10978 move_it_vertically (struct it *it, int dy)
 10979 {
 10980   if (dy <= 0)
 10981     move_it_vertically_backward (it, -dy);
 10982   else
 10983     {
 10984       move_trace ("move_it_v: from %td, %d\n", IT_CHARPOS (*it), dy);
 10985       move_it_to (it, ZV, -1, it->current_y + dy, -1,
 10986                   MOVE_TO_POS | MOVE_TO_Y);
 10987       move_trace ("move_it_v: to %td\n", IT_CHARPOS (*it));
 10988 
 10989       /* If buffer ends in ZV without a newline, move to the start of
 10990          the line to satisfy the post-condition.  */
 10991       if (IT_CHARPOS (*it) == ZV
 10992           && ZV > BEGV
 10993           && FETCH_BYTE (IT_BYTEPOS (*it) - 1) != '\n')
 10994         move_it_by_lines (it, 0);
 10995     }
 10996 }
 10997 
 10998 
 10999 /* Move iterator IT past the end of the text line it is in.  */
 11000 
 11001 void
 11002 move_it_past_eol (struct it *it)
 11003 {
 11004   enum move_it_result rc;
 11005 
 11006   rc = move_it_in_display_line_to (it, Z, 0, MOVE_TO_POS);
 11007   if (rc == MOVE_NEWLINE_OR_CR)
 11008     set_iterator_to_next (it, false);
 11009 }
 11010 
 11011 
 11012 /* Move IT by a specified number DVPOS of screen lines down.  DVPOS
 11013    negative means move up.  DVPOS == 0 means move to the start of the
 11014    screen line.
 11015 
 11016    Optimization idea: If we would know that IT->f doesn't use
 11017    a face with proportional font, we could be faster for
 11018    truncate-lines nil.  */
 11019 
 11020 void
 11021 move_it_by_lines (struct it *it, ptrdiff_t dvpos)
 11022 {
 11023 
 11024   /* The commented-out optimization uses vmotion on terminals.  This
 11025      gives bad results, because elements like it->what, on which
 11026      callers such as pos_visible_p rely, aren't updated.  */
 11027   /* struct position pos;
 11028     if (!FRAME_WINDOW_P (it->f))
 11029     {
 11030       struct text_pos textpos;
 11031 
 11032       pos = *vmotion (IT_CHARPOS (*it), dvpos, it->w);
 11033       SET_TEXT_POS (textpos, pos.bufpos, pos.bytepos);
 11034       reseat (it, textpos, true);
 11035       it->vpos += pos.vpos;
 11036       it->current_y += pos.vpos;
 11037     }
 11038     else */
 11039 
 11040   if (dvpos == 0)
 11041     {
 11042       /* DVPOS == 0 means move to the start of the screen line.  */
 11043       move_it_vertically_backward (it, 0);
 11044       /* Let next call to line_bottom_y calculate real line height.  */
 11045       last_height = 0;
 11046     }
 11047   else if (dvpos > 0)
 11048     {
 11049       move_it_to (it, -1, -1, -1, it->vpos + dvpos, MOVE_TO_VPOS);
 11050       if (!IT_POS_VALID_AFTER_MOVE_P (it))
 11051         {
 11052           /* Only move to the next buffer position if we ended up in a
 11053              string from display property, not in an overlay string
 11054              (before-string or after-string).  That is because the
 11055              latter don't conceal the underlying buffer position, so
 11056              we can ask to move the iterator to the exact position we
 11057              are interested in.  Note that, even if we are already at
 11058              IT_CHARPOS (*it), the call below is not a no-op, as it
 11059              will detect that we are at the end of the string, pop the
 11060              iterator, and compute it->current_x and it->hpos
 11061              correctly.  */
 11062           move_it_to (it, IT_CHARPOS (*it) + it->string_from_display_prop_p,
 11063                       -1, -1, -1, MOVE_TO_POS);
 11064         }
 11065     }
 11066   else
 11067     {
 11068       struct it it2;
 11069       void *it2data = NULL;
 11070       ptrdiff_t start_charpos, orig_charpos, i;
 11071       int nchars_per_row
 11072         = (it->last_visible_x - it->first_visible_x) / FRAME_COLUMN_WIDTH (it->f);
 11073       bool hit_pos_limit = false;
 11074       ptrdiff_t pos_limit;
 11075 
 11076       /* Start at the beginning of the screen line containing IT's
 11077          position.  This may actually move vertically backwards,
 11078          in case of overlays, so adjust dvpos accordingly.  */
 11079       dvpos += it->vpos;
 11080       orig_charpos = IT_CHARPOS (*it);
 11081       move_it_vertically_backward (it, 0);
 11082       dvpos -= it->vpos;
 11083 
 11084       /* Go back -DVPOS buffer lines, but no farther than -DVPOS full
 11085          screen lines, and reseat the iterator there.  */
 11086       start_charpos = IT_CHARPOS (*it);
 11087       if (it->line_wrap == TRUNCATE || nchars_per_row == 0)
 11088         pos_limit = BEGV;
 11089       else
 11090         pos_limit = max (start_charpos + dvpos * nchars_per_row, BEGV);
 11091 
 11092       for (i = -dvpos; i > 0 && IT_CHARPOS (*it) > pos_limit; --i)
 11093         back_to_previous_visible_line_start (it);
 11094       if (i > 0 && IT_CHARPOS (*it) <= pos_limit)
 11095         hit_pos_limit = true;
 11096       reseat (it, it->current.pos, true);
 11097 
 11098       /* Move further back if we end up in a string or an image.  */
 11099       while (!IT_POS_VALID_AFTER_MOVE_P (it))
 11100         {
 11101           /* First try to move to start of display line.  */
 11102           dvpos += it->vpos;
 11103           move_it_vertically_backward (it, 0);
 11104           dvpos -= it->vpos;
 11105           if (IT_POS_VALID_AFTER_MOVE_P (it))
 11106             break;
 11107           /* If start of line is still in string or image,
 11108              move further back.  */
 11109           back_to_previous_visible_line_start (it);
 11110           reseat (it, it->current.pos, true);
 11111           dvpos--;
 11112         }
 11113 
 11114       it->current_x = it->hpos = 0;
 11115 
 11116       /* Above call may have moved too far if continuation lines
 11117          are involved.  Scan forward and see if it did.  */
 11118       SAVE_IT (it2, *it, it2data);
 11119       it2.vpos = it2.current_y = 0;
 11120       move_it_to (&it2, start_charpos, -1, -1, -1, MOVE_TO_POS);
 11121       it->vpos -= it2.vpos;
 11122       it->current_y -= it2.current_y;
 11123       it->current_x = it->hpos = 0;
 11124 
 11125       /* If we moved too far back, move IT some lines forward.  */
 11126       if (it2.vpos > -dvpos)
 11127         {
 11128           int delta = it2.vpos + dvpos;
 11129 
 11130           RESTORE_IT (&it2, &it2, it2data);
 11131           SAVE_IT (it2, *it, it2data);
 11132           move_it_to (it, -1, -1, -1, it->vpos + delta, MOVE_TO_VPOS);
 11133           /* Move back again if we got too far ahead,
 11134              or didn't move at all.  */
 11135           if (it->vpos - it2.vpos > delta || IT_CHARPOS (*it) == orig_charpos)
 11136             RESTORE_IT (it, &it2, it2data);
 11137           else
 11138             bidi_unshelve_cache (it2data, true);
 11139         }
 11140       else if (hit_pos_limit && pos_limit > BEGV
 11141                && dvpos < 0 && it2.vpos < -dvpos)
 11142         {
 11143           /* If we hit the limit, but still didn't make it far enough
 11144              back, that means there's a display string with a newline
 11145              covering a large chunk of text, and that caused
 11146              back_to_previous_visible_line_start try to go too far.
 11147              Punish those who commit such atrocities by going back
 11148              until we've reached DVPOS, after lifting the limit, which
 11149              could make it slow for very long lines.  "If it hurts,
 11150              don't do that!"  */
 11151           dvpos += it2.vpos;
 11152           RESTORE_IT (it, it, it2data);
 11153           for (i = -dvpos; i > 0; --i)
 11154             {
 11155               back_to_previous_visible_line_start (it);
 11156               it->vpos--;
 11157             }
 11158           reseat_1 (it, it->current.pos, true);
 11159         }
 11160       else
 11161         RESTORE_IT (it, it, it2data);
 11162     }
 11163 }
 11164 
 11165 int
 11166 partial_line_height (struct it *it_origin)
 11167 {
 11168   /* In a buffer with very long and truncated lines, we ignore the
 11169      possibly-partial height of the last line in the window: it is too
 11170      expensive to compute that (since in most cases that involves
 11171      going all the way to ZV), and the effect of ignoring it is
 11172      relatively minor.  */
 11173   if (XBUFFER (it_origin->w->contents)->long_line_optimizations_p
 11174       && it_origin->line_wrap == TRUNCATE)
 11175     return 0;
 11176 
 11177   int partial_height;
 11178   void *it_data = NULL;
 11179   struct it it;
 11180   SAVE_IT (it, *it_origin, it_data);
 11181   move_it_to (&it, ZV, -1, it.last_visible_y, -1,
 11182               MOVE_TO_POS | MOVE_TO_Y);
 11183   if (it.what == IT_EOB)
 11184     {
 11185       int vis_height = it.last_visible_y - it.current_y;
 11186       int height = it.ascent + it.descent;
 11187       partial_height = (vis_height < height) ? vis_height : 0;
 11188     }
 11189   else
 11190     {
 11191       int last_line_y = it.current_y;
 11192       move_it_by_lines (&it, 1);
 11193       partial_height = (it.current_y > it.last_visible_y)
 11194         ? it.last_visible_y - last_line_y : 0;
 11195     }
 11196   RESTORE_IT (&it, &it, it_data);
 11197   return partial_height;
 11198 }
 11199 
 11200 /* Approximate move_it_in_display_line_to for very long and truncated
 11201    display lines, when moving horizontally.  This is used when the
 11202    buffer's long_line_optimizations_p flag is set.  It ignores various
 11203    complications, like different font sizes, invisible text, display
 11204    and overlay strings, and, to some degree, bidirectional text.  So
 11205    caveat emptor!
 11206 
 11207    Starting from IT's position, reseat IT after skipping NCHARS
 11208    characters or to the next newline/ZV, whichever comes first.  Return
 11209    what move_it_in_display_line_to would have returned in this case.  */
 11210 
 11211 static enum move_it_result
 11212 fast_move_it_horizontally (struct it *it, ptrdiff_t nchars)
 11213 {
 11214   ptrdiff_t nl_bytepos;
 11215   ptrdiff_t nl_pos = find_newline_no_quit (IT_CHARPOS (*it), IT_BYTEPOS (*it),
 11216                                            1, &nl_bytepos);
 11217   struct text_pos new_pos;
 11218   enum move_it_result move_result;
 11219 
 11220   if (nl_pos - IT_CHARPOS (*it) > nchars)
 11221     {
 11222       SET_TEXT_POS (new_pos,
 11223                     IT_CHARPOS (*it) + nchars,
 11224                     CHAR_TO_BYTE (IT_CHARPOS (*it) + nchars));
 11225       move_result = MOVE_X_REACHED;
 11226     }
 11227   else
 11228     {
 11229       if (nl_bytepos < ZV_BYTE
 11230           || (nl_bytepos > BEGV_BYTE
 11231               && FETCH_BYTE (nl_bytepos - 1) == '\n'))
 11232         {
 11233           nl_pos--;
 11234           nl_bytepos--;
 11235           move_result = MOVE_NEWLINE_OR_CR;
 11236         }
 11237       else
 11238         move_result = MOVE_POS_MATCH_OR_ZV;
 11239       SET_TEXT_POS (new_pos, nl_pos, nl_bytepos);
 11240     }
 11241   reseat (it, new_pos, false);
 11242   return move_result;
 11243 }
 11244 
 11245 /* Return true if IT points into the middle of a display vector.  */
 11246 
 11247 bool
 11248 in_display_vector_p (struct it *it)
 11249 {
 11250   return (it->method == GET_FROM_DISPLAY_VECTOR
 11251           && it->current.dpvec_index > 0
 11252           && it->dpvec + it->current.dpvec_index != it->dpend);
 11253 }
 11254 
 11255 /* This is like Fwindow_text_pixel_size but assumes that WINDOW's buffer
 11256    is the current buffer.  Fbuffer_text_pixel_size calls it after it has
 11257    set WINDOW's buffer to the buffer specified by its BUFFER_OR_NAME
 11258    argument.  */
 11259 static Lisp_Object
 11260 window_text_pixel_size (Lisp_Object window, Lisp_Object from, Lisp_Object to,
 11261                         Lisp_Object x_limit, Lisp_Object y_limit,
 11262                         Lisp_Object mode_lines, Lisp_Object ignore_line_at_end)
 11263 {
 11264   struct window *w = decode_live_window (window);
 11265   struct it it;
 11266   ptrdiff_t start, end, bpos;
 11267   struct text_pos startp;
 11268   void *itdata = NULL;
 11269   int c, max_x = 0, max_y = 0, x = 0, y = 0, vertical_offset = 0, doff = 0;
 11270 
 11271   if (NILP (from))
 11272     {
 11273       start = BEGV;
 11274       bpos = BEGV_BYTE;
 11275     }
 11276   else if (EQ (from, Qt))
 11277     {
 11278       start = BEGV;
 11279       bpos = BEGV_BYTE;
 11280       while (bpos < ZV_BYTE)
 11281         {
 11282           c = FETCH_BYTE (bpos);
 11283           if (!(c == ' ' || c == '\t' || c == '\n' || c == '\r'))
 11284             break;
 11285           inc_both (&start, &bpos);
 11286         }
 11287       while (bpos > BEGV_BYTE)
 11288         {
 11289           dec_both (&start, &bpos);
 11290           c = FETCH_BYTE (bpos);
 11291           if (!(c == ' ' || c == '\t'))
 11292             break;
 11293         }
 11294     }
 11295   else if (CONSP (from))
 11296     {
 11297       start = clip_to_bounds (BEGV, fix_position (XCAR (from)), ZV);
 11298       bpos = CHAR_TO_BYTE (start);
 11299       CHECK_FIXNUM (XCDR (from));
 11300       vertical_offset = XFIXNUM (XCDR (from));
 11301     }
 11302   else
 11303     {
 11304       start = clip_to_bounds (BEGV, fix_position (from), ZV);
 11305       bpos = CHAR_TO_BYTE (start);
 11306     }
 11307 
 11308   SET_TEXT_POS (startp, start, bpos);
 11309 
 11310   if (NILP (to))
 11311     end = ZV;
 11312   else if (EQ (to, Qt))
 11313     {
 11314       end = ZV;
 11315       bpos = ZV_BYTE;
 11316       while (bpos > BEGV_BYTE)
 11317         {
 11318           dec_both (&end, &bpos);
 11319           c = FETCH_BYTE (bpos);
 11320           if (!(c == ' ' || c == '\t' || c == '\n' || c == '\r'))
 11321             {
 11322               inc_both (&end, &bpos);
 11323               break;
 11324             }
 11325         }
 11326       while (bpos < ZV_BYTE)
 11327         {
 11328           c = fetch_char_advance (&end, &bpos);
 11329           if (!(c == ' ' || c == '\t'))
 11330             break;
 11331         }
 11332     }
 11333   else
 11334     end = clip_to_bounds (start, fix_position (to), ZV);
 11335 
 11336   if (RANGED_FIXNUMP (0, x_limit, INT_MAX))
 11337     max_x = XFIXNUM (x_limit);
 11338   else if (!NILP (x_limit))
 11339     max_x = INT_MAX;
 11340 
 11341   if (NILP (y_limit))
 11342     max_y = INT_MAX;
 11343   else if (RANGED_FIXNUMP (0, y_limit, INT_MAX))
 11344     max_y = XFIXNUM (y_limit);
 11345 
 11346   itdata = bidi_shelve_cache ();
 11347 
 11348   start_display (&it, w, startp);
 11349 
 11350   int start_y = it.current_y;
 11351 
 11352   /* It makes no sense to measure dimensions of region of text that
 11353      crosses the point where bidi reordering changes scan direction.
 11354      By using unidirectional movement here we at least support the use
 11355      case of measuring regions of text that have a uniformly R2L
 11356      directionality, and regions that begin and end in text of the
 11357      same directionality.  */
 11358   it.bidi_p = false;
 11359 
 11360   int start_x;
 11361   if (vertical_offset != 0)
 11362     {
 11363       int last_y;
 11364       it.current_y = 0;
 11365 
 11366       move_it_by_lines (&it, 0);
 11367 
 11368       /* `move_it_vertically_backward' is called by move_it_vertically
 11369          to move by a negative value (upwards), but it is not always
 11370          guaranteed to leave the iterator at or above the position
 11371          given by the offset, which this loop ensures.  */
 11372       if (vertical_offset < 0)
 11373         {
 11374           while (it.current_y > vertical_offset)
 11375             {
 11376               last_y = it.current_y;
 11377               move_it_vertically_backward (&it,
 11378                                            (abs (vertical_offset)
 11379                                             + it.current_y));
 11380 
 11381               if (it.current_y == last_y)
 11382                 break;
 11383             }
 11384         }
 11385       else
 11386         {
 11387           move_it_vertically (&it, vertical_offset);
 11388         }
 11389 
 11390       it.current_y = (WINDOW_TAB_LINE_HEIGHT (w)
 11391                       + WINDOW_HEADER_LINE_HEIGHT (w));
 11392       start = clip_to_bounds (BEGV, IT_CHARPOS (it), ZV);
 11393       start_y = it.current_y;
 11394       start_x = it.current_x;
 11395     }
 11396   else
 11397     {
 11398       /* Start at the beginning of the line containing FROM.  Otherwise
 11399          IT.current_x will be incorrectly set to zero at some arbitrary
 11400          non-zero X coordinate.  */
 11401       reseat_at_previous_visible_line_start (&it);
 11402       it.current_x = it.hpos = 0;
 11403       if (IT_CHARPOS (it) != start)
 11404         {
 11405           void *it1data = NULL;
 11406           struct it it1;
 11407 
 11408           SAVE_IT (it1, it, it1data);
 11409           move_it_to (&it, start, -1, -1, -1, MOVE_TO_POS);
 11410           /* We could have a display property at START, in which case
 11411              asking move_it_to to stop at START will overshoot and
 11412              stop at position after START.  So we try again, stopping
 11413              before START, and account for the width of the last
 11414              buffer position manually.  */
 11415           if (IT_CHARPOS (it) > start && start > BEGV)
 11416             {
 11417               ptrdiff_t it1pos = IT_CHARPOS (it1);
 11418               int it1_x = it1.current_x;
 11419 
 11420               RESTORE_IT (&it, &it1, it1data);
 11421               /* If START - 1 is the beginning of screen line,
 11422                  move_it_to will not move, so we need to use a
 11423                  lower-level move_it_in_display_line subroutine, and
 11424                  tell it to move just 1 pixel, so it stops at the next
 11425                  display element.  */
 11426               if (start - 1 > it1pos)
 11427                 move_it_to (&it, start - 1, -1, -1, -1, MOVE_TO_POS);
 11428               else
 11429                 move_it_in_display_line (&it, start, it1_x + 1,
 11430                                          MOVE_TO_POS | MOVE_TO_X);
 11431               move_it_to (&it, start - 1, -1, -1, -1, MOVE_TO_POS);
 11432               start_x = it.current_x;
 11433               /* If we didn't change our buffer position, the pixel
 11434                  width of what's here was not yet accounted for; do it
 11435                  manually.  */
 11436               if (IT_CHARPOS (it) == start - 1)
 11437                 start_x += it.pixel_width;
 11438             }
 11439           else
 11440             {
 11441               start_x = it.current_x;
 11442               bidi_unshelve_cache (it1data, true);
 11443             }
 11444         }
 11445       else
 11446         start_x = it.current_x;
 11447     }
 11448 
 11449   /* Now move to TO.  */
 11450   int move_op = MOVE_TO_POS | MOVE_TO_Y;
 11451   int to_x = -1;
 11452   it.current_y = start_y;
 11453   /* If FROM is on a newline, pretend that we start at the beginning
 11454      of the next line, because the newline takes no place on display.  */
 11455   if (FETCH_BYTE (start) == '\n')
 11456     it.current_x = 0;
 11457   if (!NILP (x_limit))
 11458     {
 11459       it.last_visible_x = max_x;
 11460       /* Actually, we never want move_it_to stop at to_x.  But to make
 11461          sure that move_it_in_display_line_to always moves far enough,
 11462          we set to_x to INT_MAX and specify MOVE_TO_X.  */
 11463       move_op |= MOVE_TO_X;
 11464       to_x = INT_MAX;
 11465     }
 11466 
 11467   void *it2data = NULL;
 11468   struct it it2;
 11469   SAVE_IT (it2, it, it2data);
 11470 
 11471   x = move_it_to (&it, end, to_x, max_y, -1, move_op);
 11472 
 11473   /* We could have a display property at END, in which case asking
 11474      move_it_to to stop at END will overshoot and stop at position
 11475      after END.  So we try again, stopping before END, and account for
 11476      the width of the last buffer position manually.  */
 11477   if (IT_CHARPOS (it) > end)
 11478     {
 11479       end--;
 11480       RESTORE_IT (&it, &it2, it2data);
 11481       x = move_it_to (&it, end, to_x, max_y, -1, move_op);
 11482       /* Add the width of the thing at TO, but only if we didn't
 11483          overshoot it; if we did, it is already accounted for.  Also,
 11484          account for the height of the thing at TO.  */
 11485       if (IT_CHARPOS (it) == end)
 11486         {
 11487           x += it.pixel_width;
 11488 
 11489           /* DTRT if ignore_line_at_end is t.  */
 11490           if (!NILP (ignore_line_at_end))
 11491             doff = (max (it.max_ascent, it.ascent)
 11492                     + max (it.max_descent, it.descent));
 11493           else
 11494             {
 11495               it.max_ascent = max (it.max_ascent, it.ascent);
 11496               it.max_descent = max (it.max_descent, it.descent);
 11497             }
 11498         }
 11499     }
 11500   else
 11501     bidi_unshelve_cache (it2data, true);
 11502 
 11503   if (!NILP (x_limit))
 11504     {
 11505       /* Don't return more than X-LIMIT.  */
 11506       if (x > max_x)
 11507         x = max_x;
 11508     }
 11509 
 11510   /* If text spans more than one screen line, we don't need to adjust
 11511      the x-span for start_x, since the second and subsequent lines
 11512      will begin at zero X coordinate.  */
 11513   if (it.current_y > start_y)
 11514     start_x = 0;
 11515 
 11516   /* Subtract height of header-line and tab-line which was counted
 11517      automatically by start_display.  */
 11518   if (!NILP (ignore_line_at_end))
 11519     y = (it.current_y + doff
 11520          - WINDOW_TAB_LINE_HEIGHT (w)
 11521          - WINDOW_HEADER_LINE_HEIGHT (w));
 11522   else
 11523     y = (it.current_y + it.max_ascent + it.max_descent + doff
 11524          - WINDOW_TAB_LINE_HEIGHT (w) - WINDOW_HEADER_LINE_HEIGHT (w));
 11525 
 11526   /* Don't return more than Y-LIMIT.  */
 11527   if (y > max_y)
 11528     y = max_y;
 11529 
 11530   if ((EQ (mode_lines, Qtab_line) || EQ (mode_lines, Qt))
 11531       && window_wants_tab_line (w))
 11532     /* Add height of tab-line as requested.  */
 11533     {
 11534       Lisp_Object window_tab_line_format
 11535         = window_parameter (w, Qtab_line_format);
 11536 
 11537       y = y + display_mode_line (w, TAB_LINE_FACE_ID,
 11538                                  NILP (window_tab_line_format)
 11539                                  ? BVAR (current_buffer, tab_line_format)
 11540                                  : window_tab_line_format);
 11541     }
 11542 
 11543   if ((EQ (mode_lines, Qheader_line) || EQ (mode_lines, Qt))
 11544       && window_wants_header_line (w))
 11545     {
 11546       Lisp_Object window_header_line_format
 11547         = window_parameter (w, Qheader_line_format);
 11548 
 11549       y = y + display_mode_line (w, HEADER_LINE_FACE_ID,
 11550                                  NILP (window_header_line_format)
 11551                                  ? BVAR (current_buffer, header_line_format)
 11552                                  : window_header_line_format);
 11553     }
 11554 
 11555   if ((EQ (mode_lines, Qmode_line) || EQ (mode_lines, Qt))
 11556       && window_wants_mode_line (w))
 11557     {
 11558       Lisp_Object window_mode_line_format
 11559         = window_parameter (w, Qmode_line_format);
 11560 
 11561       y = y + display_mode_line (w, CURRENT_MODE_LINE_ACTIVE_FACE_ID (w),
 11562                                  NILP (window_mode_line_format)
 11563                                  ? BVAR (current_buffer, mode_line_format)
 11564                                  : window_mode_line_format);
 11565     }
 11566 
 11567   bidi_unshelve_cache (itdata, false);
 11568 
 11569   return (!vertical_offset
 11570           ? Fcons (make_fixnum (x - start_x), make_fixnum (y))
 11571           : list3i (x - start_x, y, start));
 11572 }
 11573 
 11574 DEFUN ("window-text-pixel-size", Fwindow_text_pixel_size, Swindow_text_pixel_size, 0, 7, 0,
 11575        doc: /* Return the size of the text of WINDOW's buffer in pixels.
 11576 WINDOW must be a live window and defaults to the selected one.  The
 11577 return value is a cons of the maximum pixel-width of any text line and
 11578 the pixel-height of all the text lines in the accessible portion of
 11579 buffer text.
 11580 
 11581 If FROM is a cons cell, the return value includes, in addition to the
 11582 dimensions, also a third element that provides the buffer position
 11583 from which measuring of the text dimensions was actually started.
 11584 
 11585 This function exists to allow Lisp programs to adjust the dimensions
 11586 of WINDOW to the buffer text it needs to display.
 11587 
 11588 The optional argument FROM, if non-nil, specifies the first text
 11589 position to consider, and defaults to the minimum accessible position
 11590 of the buffer.  If FROM is a cons, its car specifies a buffer
 11591 position, and its cdr specifies the vertical offset in pixels from
 11592 that position to the first screen line to be measured.  If FROM is t,
 11593 it stands for the minimum accessible position that starts a non-empty
 11594 line.  TO, if non-nil, specifies the last text position and defaults
 11595 to the maximum accessible position of the buffer.  If TO is t, it
 11596 stands for the maximum accessible position that ends a non-empty line.
 11597 
 11598 The optional argument X-LIMIT, if non-nil, specifies the maximum X
 11599 coordinate beyond which the text should be ignored.  It is therefore
 11600 also the maximum width that the function can return.  X-LIMIT nil or
 11601 omitted means to use the pixel-width of WINDOW's body.  This default
 11602 means text of truncated lines wider than the window will be ignored;
 11603 specify a non-nil value for X-LIMIT if lines are truncated and you need
 11604 to account for the truncated text.
 11605 
 11606 Use nil for X-LIMIT if you want to know how high WINDOW should become in
 11607 order to fit all of its buffer's text with the width of WINDOW
 11608 unaltered.  Use the maximum width WINDOW may assume if you intend to
 11609 change WINDOW's width.  Use t for the maximum possible value.  Since
 11610 calculating the width of long lines can take some time, it's always a
 11611 good idea to make this argument as small as possible; in particular, if
 11612 the buffer contains long lines that shall be truncated anyway.
 11613 
 11614 The optional argument Y-LIMIT, if non-nil, specifies the maximum Y
 11615 coordinate beyond which the text is to be ignored; it is therefore
 11616 also the maximum height that the function can return (excluding the
 11617 height of the mode- or header-line, if any).  Y-LIMIT nil or omitted
 11618 means consider all of the accessible portion of buffer text up to the
 11619 position specified by TO.  Since calculating the text height of a
 11620 large buffer can take some time, it makes sense to specify this
 11621 argument if the size of the buffer is large or unknown.
 11622 
 11623 Optional argument MODE-LINES nil or omitted means do not include the
 11624 height of the mode-, tab- or header-line of WINDOW in the return value.
 11625 If it is the symbol `mode-line', `tab-line' or `header-line', include
 11626 only the height of that line, if present, in the return value.  If t,
 11627 include the height of any of these, if present, in the return value.
 11628 
 11629 IGNORE-LINE-AT-END, if non-nil, means to not add the height of the
 11630 screen line that includes TO to the returned height of the text.  */)
 11631   (Lisp_Object window, Lisp_Object from, Lisp_Object to, Lisp_Object x_limit,
 11632    Lisp_Object y_limit, Lisp_Object mode_lines, Lisp_Object ignore_line_at_end)
 11633 {
 11634   struct window *w = decode_live_window (window);
 11635   struct buffer *b = XBUFFER (w->contents);
 11636   struct buffer *old_b = NULL;
 11637   Lisp_Object value;
 11638 
 11639   if (b != current_buffer)
 11640     {
 11641       old_b = current_buffer;
 11642       set_buffer_internal_1 (b);
 11643     }
 11644 
 11645   value = window_text_pixel_size (window, from, to, x_limit, y_limit, mode_lines,
 11646                                   ignore_line_at_end);
 11647 
 11648   if (old_b)
 11649     set_buffer_internal_1 (old_b);
 11650 
 11651   return value;
 11652 }
 11653 
 11654 DEFUN ("buffer-text-pixel-size", Fbuffer_text_pixel_size, Sbuffer_text_pixel_size, 0, 4, 0,
 11655        doc: /* Return size of whole text of BUFFER-OR-NAME in WINDOW.
 11656 BUFFER-OR-NAME must specify a live buffer or the name of a live buffer
 11657 and defaults to the current buffer.  WINDOW must be a live window and
 11658 defaults to the selected one.  The return value is a cons of the maximum
 11659 pixel-width of any text line and the pixel-height of all the text lines
 11660 of the buffer specified by BUFFER-OR-NAME.
 11661 
 11662 The optional arguments X-LIMIT and Y-LIMIT have the same meaning as with
 11663 `window-text-pixel-size'.
 11664 
 11665 Do not use this function if the buffer specified by BUFFER-OR-NAME is
 11666 already displayed in WINDOW.  `window-text-pixel-size' is cheaper in
 11667 that case because it does not have to temporarily show that buffer in
 11668 WINDOW.  */)
 11669   (Lisp_Object buffer_or_name, Lisp_Object window, Lisp_Object x_limit,
 11670    Lisp_Object y_limit)
 11671 {
 11672   struct window *w = decode_live_window (window);
 11673   struct buffer *b = (NILP (buffer_or_name)
 11674                       ? current_buffer
 11675                       : XBUFFER (Fget_buffer (buffer_or_name)));
 11676   Lisp_Object buffer, value;
 11677   specpdl_ref count = SPECPDL_INDEX ();
 11678 
 11679   XSETBUFFER (buffer, b);
 11680 
 11681   /* The unwind form of with_echo_area_buffer is what we need here to
 11682      make WINDOW temporarily show our buffer.  */
 11683   /* FIXME: Can we move this into the `if (!EQ (buffer, w->contents))`?  */
 11684   record_unwind_protect (unwind_with_echo_area_buffer,
 11685                          with_echo_area_buffer_unwind_data (w));
 11686 
 11687   set_buffer_internal_1 (b);
 11688 
 11689   ptrdiff_t base_line_pos = w->base_line_pos;
 11690   int end_valid = w->window_end_valid;
 11691   if (!EQ (buffer, w->contents))
 11692     {
 11693       wset_buffer (w, buffer);
 11694       set_marker_both (w->pointm, buffer, BEG, BEG_BYTE);
 11695       set_marker_both (w->old_pointm, buffer, BEG, BEG_BYTE);
 11696     }
 11697 
 11698   value = window_text_pixel_size (window, Qnil, Qnil, x_limit, y_limit, Qnil,
 11699                                   Qnil);
 11700 
 11701   unbind_to (count, Qnil);
 11702 
 11703   /* Restore original values.  This is important if this function is
 11704      called from some ':eval' form in the middle of redisplay.  */
 11705   w->base_line_pos = base_line_pos;
 11706   w->window_end_valid = end_valid;
 11707 
 11708   return value;
 11709 }
 11710 
 11711 
 11712 DEFUN ("display--line-is-continued-p", Fdisplay__line_is_continued_p,
 11713        Sdisplay__line_is_continued_p, 0, 0, 0,
 11714        doc: /* Return non-nil if the current screen line is continued on display.  */)
 11715   (void)
 11716 {
 11717   struct buffer *oldb = current_buffer;
 11718   struct window *w = XWINDOW (selected_window);
 11719   enum move_it_result rc = MOVE_POS_MATCH_OR_ZV;
 11720 
 11721   set_buffer_internal_1 (XBUFFER (w->contents));
 11722 
 11723   if (PT < ZV)
 11724     {
 11725       struct text_pos startpos;
 11726       struct it it;
 11727       void *itdata;
 11728       /* Use a marker, since vertical-motion enters redisplay, which can
 11729          trigger fontifications, which in turn could modify buffer text.  */
 11730       Lisp_Object opoint = Fpoint_marker ();
 11731 
 11732       /* Make sure to start from the beginning of the current screen
 11733          line, so that move_it_in_display_line_to counts pixels correctly.  */
 11734       Fvertical_motion (make_fixnum (0), selected_window, Qnil);
 11735       SET_TEXT_POS (startpos, PT, PT_BYTE);
 11736       itdata = bidi_shelve_cache ();
 11737       start_display (&it, w, startpos);
 11738       /* If lines are truncated, no line is continued.  */
 11739       if (it.line_wrap != TRUNCATE)
 11740         {
 11741           it.glyph_row = NULL;
 11742           rc = move_it_in_display_line_to (&it, ZV, -1, MOVE_TO_POS);
 11743         }
 11744       SET_PT_BOTH (marker_position (opoint), marker_byte_position (opoint));
 11745       bidi_unshelve_cache (itdata, false);
 11746     }
 11747   set_buffer_internal_1 (oldb);
 11748 
 11749   return rc == MOVE_LINE_CONTINUED ? Qt : Qnil;
 11750 }
 11751 
 11752 
 11753 /***********************************************************************
 11754                                Messages
 11755  ***********************************************************************/
 11756 
 11757 /* Return the number of arguments the format string FORMAT needs.  */
 11758 
 11759 static ptrdiff_t
 11760 format_nargs (char const *format)
 11761 {
 11762   ptrdiff_t nargs = 0;
 11763   for (char const *p = format; (p = strchr (p, '%')); p++)
 11764     if (p[1] == '%')
 11765       p++;
 11766     else
 11767       nargs++;
 11768   return nargs;
 11769 }
 11770 
 11771 /* Add a message with format string FORMAT and formatted arguments
 11772    to *Messages*.  */
 11773 
 11774 void
 11775 add_to_log (const char *format, ...)
 11776 {
 11777   va_list ap;
 11778   va_start (ap, format);
 11779   vadd_to_log (format, ap);
 11780   va_end (ap);
 11781 }
 11782 
 11783 void
 11784 vadd_to_log (char const *format, va_list ap)
 11785 {
 11786   ptrdiff_t form_nargs = format_nargs (format);
 11787   ptrdiff_t nargs = 1 + form_nargs;
 11788   Lisp_Object args[10];
 11789   eassert (nargs <= ARRAYELTS (args));
 11790   AUTO_STRING (args0, format);
 11791   args[0] = args0;
 11792   for (ptrdiff_t i = 1; i <= nargs; i++)
 11793     args[i] = va_arg (ap, Lisp_Object);
 11794   Lisp_Object msg = Qnil;
 11795   msg = Fformat_message (nargs, args);
 11796 
 11797   ptrdiff_t len = SBYTES (msg) + 1;
 11798   USE_SAFE_ALLOCA;
 11799   char *buffer = SAFE_ALLOCA (len);
 11800   memcpy (buffer, SDATA (msg), len);
 11801 
 11802   message_dolog (buffer, len - 1, true, STRING_MULTIBYTE (msg));
 11803   SAFE_FREE ();
 11804 }
 11805 
 11806 
 11807 /* Output a newline in the *Messages* buffer if "needs" one.  */
 11808 
 11809 void
 11810 message_log_maybe_newline (void)
 11811 {
 11812   if (message_log_need_newline)
 11813     message_dolog ("", 0, true, false);
 11814 }
 11815 
 11816 
 11817 /* Add a string M of length NBYTES to the message log, optionally
 11818    terminated with a newline when NLFLAG is true.  MULTIBYTE, if
 11819    true, means interpret the contents of M as multibyte.  This
 11820    function calls low-level routines in order to bypass text property
 11821    hooks, etc. which might not be safe to run.
 11822 
 11823    This may GC (insert may run before/after change hooks),
 11824    so the buffer M must NOT point to a Lisp string.  */
 11825 
 11826 void
 11827 message_dolog (const char *m, ptrdiff_t nbytes, bool nlflag, bool multibyte)
 11828 {
 11829   const unsigned char *msg = (const unsigned char *) m;
 11830 
 11831   if (!NILP (Vmemory_full))
 11832     return;
 11833 
 11834   if (!NILP (Vmessage_log_max))
 11835     {
 11836       struct buffer *oldbuf;
 11837       Lisp_Object oldpoint, oldbegv, oldzv;
 11838       int old_windows_or_buffers_changed = windows_or_buffers_changed;
 11839       ptrdiff_t point_at_end = 0;
 11840       ptrdiff_t zv_at_end = 0;
 11841       Lisp_Object old_deactivate_mark;
 11842 
 11843       old_deactivate_mark = Vdeactivate_mark;
 11844       oldbuf = current_buffer;
 11845 
 11846       /* Sanity check, in case the variable has been set to something
 11847          invalid.  */
 11848       if (! STRINGP (Vmessages_buffer_name))
 11849         Vmessages_buffer_name = build_string ("*Messages*");
 11850       /* Ensure the Messages buffer exists, and switch to it.
 11851          If we created it, set the major-mode.  */
 11852       bool newbuffer = NILP (Fget_buffer (Vmessages_buffer_name));
 11853       Fset_buffer (Fget_buffer_create (Vmessages_buffer_name, Qnil));
 11854       if (newbuffer
 11855           && !NILP (Ffboundp (intern ("messages-buffer-mode"))))
 11856         call0 (intern ("messages-buffer-mode"));
 11857 
 11858       bset_undo_list (current_buffer, Qt);
 11859       bset_cache_long_scans (current_buffer, Qnil);
 11860 
 11861       oldpoint = message_dolog_marker1;
 11862       set_marker_restricted_both (oldpoint, Qnil, PT, PT_BYTE);
 11863       oldbegv = message_dolog_marker2;
 11864       set_marker_restricted_both (oldbegv, Qnil, BEGV, BEGV_BYTE);
 11865       oldzv = message_dolog_marker3;
 11866       set_marker_restricted_both (oldzv, Qnil, ZV, ZV_BYTE);
 11867 
 11868       if (PT == Z)
 11869         point_at_end = 1;
 11870       if (ZV == Z)
 11871         zv_at_end = 1;
 11872 
 11873       BEGV = BEG;
 11874       BEGV_BYTE = BEG_BYTE;
 11875       ZV = Z;
 11876       ZV_BYTE = Z_BYTE;
 11877       TEMP_SET_PT_BOTH (Z, Z_BYTE);
 11878 
 11879       /* Insert the string--maybe converting multibyte to single byte
 11880          or vice versa, so that all the text fits the buffer.  */
 11881       if (multibyte
 11882           && NILP (BVAR (current_buffer, enable_multibyte_characters)))
 11883         {
 11884           /* Convert a multibyte string to single-byte
 11885              for the *Message* buffer.  */
 11886           for (ptrdiff_t i = 0; i < nbytes; )
 11887             {
 11888               int char_bytes, c = check_char_and_length (msg + i, &char_bytes);
 11889               char work = CHAR_TO_BYTE8 (c);
 11890               insert_1_both (&work, 1, 1, true, false, false);
 11891               i += char_bytes;
 11892             }
 11893         }
 11894       else if (! multibyte
 11895                && ! NILP (BVAR (current_buffer, enable_multibyte_characters)))
 11896         {
 11897           /* Convert a single-byte string to multibyte
 11898              for the *Message* buffer.  */
 11899           for (ptrdiff_t i = 0; i < nbytes; i++)
 11900             {
 11901               int c = make_char_multibyte (msg[i]);
 11902               unsigned char str[MAX_MULTIBYTE_LENGTH];
 11903               int char_bytes = CHAR_STRING (c, str);
 11904               insert_1_both ((char *) str, 1, char_bytes, true, false, false);
 11905             }
 11906         }
 11907       else if (nbytes)
 11908         insert_1_both (m, chars_in_text (msg, nbytes), nbytes,
 11909                        true, false, false);
 11910 
 11911       if (nlflag)
 11912         {
 11913           ptrdiff_t this_bol, this_bol_byte, prev_bol, prev_bol_byte;
 11914           intmax_t dups;
 11915 
 11916           /* Since we call del_range_both passing false for PREPARE,
 11917              we aren't prepared to run modification hooks (we could
 11918              end up calling modification hooks from another buffer and
 11919              only with AFTER=t, Bug#21824).  */
 11920           specpdl_ref count = SPECPDL_INDEX ();
 11921           specbind (Qinhibit_modification_hooks, Qt);
 11922 
 11923           insert_1_both ("\n", 1, 1, true, false, false);
 11924 
 11925           scan_newline (Z, Z_BYTE, BEG, BEG_BYTE, -2, false);
 11926           this_bol = PT;
 11927           this_bol_byte = PT_BYTE;
 11928 
 11929           /* See if this line duplicates the previous one.
 11930              If so, combine duplicates.  */
 11931           if (this_bol > BEG)
 11932             {
 11933               scan_newline (PT, PT_BYTE, BEG, BEG_BYTE, -2, false);
 11934               prev_bol = PT;
 11935               prev_bol_byte = PT_BYTE;
 11936 
 11937               dups = message_log_check_duplicate (prev_bol_byte,
 11938                                                   this_bol_byte);
 11939               if (dups)
 11940                 {
 11941                   del_range_both (prev_bol, prev_bol_byte,
 11942                                   this_bol, this_bol_byte, false);
 11943                   if (dups > 1)
 11944                     {
 11945                       char dupstr[sizeof " [ times]"
 11946                                   + INT_STRLEN_BOUND (dups)];
 11947 
 11948                       /* If you change this format, don't forget to also
 11949                          change message_log_check_duplicate.  */
 11950                       int duplen = sprintf (dupstr, " [%"PRIdMAX" times]",
 11951                                             dups);
 11952                       TEMP_SET_PT_BOTH (Z - 1, Z_BYTE - 1);
 11953                       insert_1_both (dupstr, duplen, duplen,
 11954                                      true, false, true);
 11955                     }
 11956                 }
 11957             }
 11958 
 11959           /* If we have more than the desired maximum number of lines
 11960              in the *Messages* buffer now, delete the oldest ones.
 11961              This is safe because we don't have undo in this buffer.  */
 11962 
 11963           if (FIXNATP (Vmessage_log_max))
 11964             {
 11965               scan_newline (Z, Z_BYTE, BEG, BEG_BYTE,
 11966                             -XFIXNAT (Vmessage_log_max) - 1, false);
 11967               del_range_both (BEG, BEG_BYTE, PT, PT_BYTE, false);
 11968             }
 11969 
 11970           unbind_to (count, Qnil);
 11971         }
 11972       BEGV = marker_position (oldbegv);
 11973       BEGV_BYTE = marker_byte_position (oldbegv);
 11974 
 11975       if (zv_at_end)
 11976         {
 11977           ZV = Z;
 11978           ZV_BYTE = Z_BYTE;
 11979         }
 11980       else
 11981         {
 11982           ZV = marker_position (oldzv);
 11983           ZV_BYTE = marker_byte_position (oldzv);
 11984         }
 11985 
 11986       if (point_at_end)
 11987         TEMP_SET_PT_BOTH (Z, Z_BYTE);
 11988       else
 11989         /* We can't do Fgoto_char (oldpoint) because it will run some
 11990            Lisp code.  */
 11991         TEMP_SET_PT_BOTH (marker_position (oldpoint),
 11992                           marker_byte_position (oldpoint));
 11993 
 11994       unchain_marker (XMARKER (oldpoint));
 11995       unchain_marker (XMARKER (oldbegv));
 11996       unchain_marker (XMARKER (oldzv));
 11997 
 11998       /* We called insert_1_both above with its 5th argument (PREPARE)
 11999          false, which prevents insert_1_both from calling
 12000          prepare_to_modify_buffer, which in turns prevents us from
 12001          incrementing windows_or_buffers_changed even if *Messages* is
 12002          shown in some window.  So we must manually set
 12003          windows_or_buffers_changed here to make up for that.  */
 12004       windows_or_buffers_changed = old_windows_or_buffers_changed;
 12005       bset_redisplay (current_buffer);
 12006 
 12007       set_buffer_internal (oldbuf);
 12008 
 12009       message_log_need_newline = !nlflag;
 12010       Vdeactivate_mark = old_deactivate_mark;
 12011     }
 12012 }
 12013 
 12014 
 12015 /* We are at the end of the buffer after just having inserted a newline.
 12016    (Note: We depend on the fact we won't be crossing the gap.)
 12017    Check to see if the most recent message looks a lot like the previous one.
 12018    Return 0 if different, 1 if the new one should just replace it, or a
 12019    value N > 1 if we should also append " [N times]".  */
 12020 
 12021 static intmax_t
 12022 message_log_check_duplicate (ptrdiff_t prev_bol_byte, ptrdiff_t this_bol_byte)
 12023 {
 12024   ptrdiff_t i;
 12025   ptrdiff_t len = Z_BYTE - 1 - this_bol_byte;
 12026   bool seen_dots = false;
 12027   unsigned char *p1 = BUF_BYTE_ADDRESS (current_buffer, prev_bol_byte);
 12028   unsigned char *p2 = BUF_BYTE_ADDRESS (current_buffer, this_bol_byte);
 12029 
 12030   for (i = 0; i < len; i++)
 12031     {
 12032       if (i >= 3 && p1[i - 3] == '.' && p1[i - 2] == '.' && p1[i - 1] == '.')
 12033         seen_dots = true;
 12034       if (p1[i] != p2[i])
 12035         return seen_dots;
 12036     }
 12037   p1 += len;
 12038   if (*p1 == '\n')
 12039     return 2;
 12040   if (*p1++ == ' ' && *p1++ == '[')
 12041     {
 12042       char *pend;
 12043       intmax_t n = strtoimax ((char *) p1, &pend, 10);
 12044       if (0 < n && n < INTMAX_MAX && strncmp (pend, " times]\n", 8) == 0)
 12045         return n + 1;
 12046     }
 12047   return 0;
 12048 }
 12049 
 12050 
 12051 /* Display an echo area message M with a specified length of NBYTES
 12052    bytes.  The string may include null characters.  If M is not a
 12053    string, clear out any existing message, and let the mini-buffer
 12054    text show through.
 12055 
 12056    This function cancels echoing.  */
 12057 
 12058 void
 12059 message3 (Lisp_Object m)
 12060 {
 12061   clear_message (true, true);
 12062   cancel_echoing ();
 12063 
 12064   /* First flush out any partial line written with print.  */
 12065   message_log_maybe_newline ();
 12066   if (STRINGP (m))
 12067     {
 12068       ptrdiff_t nbytes = SBYTES (m);
 12069       bool multibyte = STRING_MULTIBYTE (m);
 12070       char *buffer;
 12071       USE_SAFE_ALLOCA;
 12072       SAFE_ALLOCA_STRING (buffer, m);
 12073       message_dolog (buffer, nbytes, true, multibyte);
 12074       SAFE_FREE ();
 12075     }
 12076   if (! inhibit_message)
 12077     message3_nolog (m);
 12078 }
 12079 
 12080 /* Log the message M to stderr.  Log an empty line if M is not a string.  */
 12081 
 12082 static void
 12083 message_to_stderr (Lisp_Object m)
 12084 {
 12085   if (noninteractive_need_newline)
 12086     {
 12087       noninteractive_need_newline = false;
 12088       errputc ('\n');
 12089     }
 12090   if (STRINGP (m))
 12091     {
 12092       Lisp_Object coding_system = Vlocale_coding_system;
 12093       Lisp_Object s;
 12094 
 12095       if (!NILP (Vcoding_system_for_write))
 12096         coding_system = Vcoding_system_for_write;
 12097       if (!NILP (coding_system))
 12098         s = code_convert_string_norecord (m, coding_system, true);
 12099       else
 12100         s = m;
 12101 
 12102       errwrite (SDATA (s), SBYTES (s));
 12103     }
 12104   if (STRINGP (m) || !cursor_in_echo_area)
 12105     errputc ('\n');
 12106 }
 12107 
 12108 /* The non-logging version of message3.
 12109    This does not cancel echoing, because it is used for echoing.
 12110    Perhaps we need to make a separate function for echoing
 12111    and make this cancel echoing.  */
 12112 
 12113 void
 12114 message3_nolog (Lisp_Object m)
 12115 {
 12116   struct frame *sf = SELECTED_FRAME ();
 12117 
 12118   if (FRAME_INITIAL_P (sf))
 12119     message_to_stderr (m);
 12120   /* Error messages get reported properly by cmd_error, so this must be just an
 12121      informative message; if the frame hasn't really been initialized yet, just
 12122      toss it.  */
 12123   else if (INTERACTIVE && sf->glyphs_initialized_p)
 12124     {
 12125       /* Get the frame containing the mini-buffer
 12126          that the selected frame is using.  */
 12127       Lisp_Object mini_window = FRAME_MINIBUF_WINDOW (sf);
 12128       Lisp_Object frame = XWINDOW (mini_window)->frame;
 12129       struct frame *f = XFRAME (frame);
 12130 
 12131       if (FRAME_VISIBLE_P (sf) && !FRAME_VISIBLE_P (f))
 12132         Fmake_frame_visible (frame);
 12133 
 12134       if (STRINGP (m) && SCHARS (m) > 0)
 12135         {
 12136           set_message (m);
 12137           if (minibuffer_auto_raise)
 12138             Fraise_frame (frame);
 12139           /* Assume we are not echoing.
 12140              (If we are, echo_now will override this.)  */
 12141           echo_message_buffer = Qnil;
 12142         }
 12143       else
 12144         clear_message (true, true);
 12145 
 12146       do_pending_window_change (false);
 12147       echo_area_display (true);
 12148       do_pending_window_change (false);
 12149       if (FRAME_TERMINAL (f)->frame_up_to_date_hook)
 12150         (*FRAME_TERMINAL (f)->frame_up_to_date_hook) (f);
 12151     }
 12152 }
 12153 
 12154 
 12155 /* Display a null-terminated echo area message M.  If M is 0, clear
 12156    out any existing message, and let the mini-buffer text show through.
 12157 
 12158    The buffer M must continue to exist until after the echo area gets
 12159    cleared or some other message gets displayed there.  Do not pass
 12160    text that is stored in a Lisp string.  Do not pass text in a buffer
 12161    that was alloca'd.  */
 12162 
 12163 void
 12164 message1 (const char *m)
 12165 {
 12166   message3 (m ? build_unibyte_string (m) : Qnil);
 12167 }
 12168 
 12169 
 12170 /* The non-logging counterpart of message1.  */
 12171 
 12172 void
 12173 message1_nolog (const char *m)
 12174 {
 12175   message3_nolog (m ? build_unibyte_string (m) : Qnil);
 12176 }
 12177 
 12178 /* Display a message M which contains a single %s
 12179    which gets replaced with STRING.  */
 12180 
 12181 void
 12182 message_with_string (const char *m, Lisp_Object string, bool log)
 12183 {
 12184   CHECK_STRING (string);
 12185 
 12186   bool need_message;
 12187   if (noninteractive)
 12188     need_message = !!m;
 12189   else if (!INTERACTIVE)
 12190     need_message = false;
 12191   else
 12192     {
 12193       /* The frame whose minibuffer we're going to display the message on.
 12194          It may be larger than the selected frame, so we need
 12195          to use its buffer, not the selected frame's buffer.  */
 12196       Lisp_Object mini_window;
 12197       struct frame *f, *sf = SELECTED_FRAME ();
 12198 
 12199       /* Get the frame containing the minibuffer
 12200          that the selected frame is using.  */
 12201       mini_window = FRAME_MINIBUF_WINDOW (sf);
 12202       f = XFRAME (WINDOW_FRAME (XWINDOW (mini_window)));
 12203 
 12204       /* Error messages get reported properly by cmd_error, so this must be
 12205          just an informative message; if the frame hasn't really been
 12206          initialized yet, just toss it.  */
 12207       need_message = f->glyphs_initialized_p;
 12208     }
 12209 
 12210   if (need_message)
 12211     {
 12212       AUTO_STRING (fmt, m);
 12213       Lisp_Object msg = CALLN (Fformat_message, fmt, string);
 12214 
 12215       if (noninteractive)
 12216         message_to_stderr (msg);
 12217       else
 12218         {
 12219           if (log)
 12220             message3 (msg);
 12221           else
 12222             message3_nolog (msg);
 12223 
 12224           /* Print should start at the beginning of the message
 12225              buffer next time.  */
 12226           message_buf_print = false;
 12227         }
 12228     }
 12229 }
 12230 
 12231 
 12232 /* Dump an informative message to the minibuf.  If M is 0, clear out
 12233    any existing message, and let the mini-buffer text show through.
 12234 
 12235    The message must be safe ASCII (because when Emacs is
 12236    non-interactive the message is sent straight to stderr without
 12237    encoding first) and the format must not contain ` or ' (because
 12238    this function does not account for `text-quoting-style').  If your
 12239    message and format do not fit into this category, convert your
 12240    arguments to Lisp objects and use Fmessage instead.  */
 12241 
 12242 static void ATTRIBUTE_FORMAT_PRINTF (1, 0)
 12243 vmessage (const char *m, va_list ap)
 12244 {
 12245   if (noninteractive)
 12246     {
 12247       if (m)
 12248         {
 12249           if (noninteractive_need_newline)
 12250             putc ('\n', stderr);
 12251           noninteractive_need_newline = false;
 12252           vfprintf (stderr, m, ap);
 12253           if (!cursor_in_echo_area)
 12254             putc ('\n', stderr);
 12255           fflush (stderr);
 12256         }
 12257     }
 12258   else if (INTERACTIVE)
 12259     {
 12260       /* The frame whose mini-buffer we're going to display the message
 12261          on.  It may be larger than the selected frame, so we need to
 12262          use its buffer, not the selected frame's buffer.  */
 12263       Lisp_Object mini_window;
 12264       struct frame *f, *sf = SELECTED_FRAME ();
 12265 
 12266       /* Get the frame containing the mini-buffer
 12267          that the selected frame is using.  */
 12268       mini_window = FRAME_MINIBUF_WINDOW (sf);
 12269       f = XFRAME (WINDOW_FRAME (XWINDOW (mini_window)));
 12270 
 12271       /* Error messages get reported properly by cmd_error, so this must be
 12272          just an informative message; if the frame hasn't really been
 12273          initialized yet, just toss it.  */
 12274       if (f->glyphs_initialized_p)
 12275         {
 12276           if (m)
 12277             {
 12278               ptrdiff_t len;
 12279               ptrdiff_t maxsize = FRAME_MESSAGE_BUF_SIZE (f);
 12280               USE_SAFE_ALLOCA;
 12281               char *message_buf = SAFE_ALLOCA (maxsize + 1);
 12282 
 12283               len = doprnt (message_buf, maxsize, m, 0, ap);
 12284 
 12285               message3 (make_string (message_buf, len));
 12286               SAFE_FREE ();
 12287             }
 12288           else
 12289             message1 (0);
 12290 
 12291           /* Print should start at the beginning of the message
 12292              buffer next time.  */
 12293           message_buf_print = false;
 12294         }
 12295     }
 12296 }
 12297 
 12298 /* See vmessage for restrictions on the text of the message.  */
 12299 void
 12300 message (const char *m, ...)
 12301 {
 12302   va_list ap;
 12303   va_start (ap, m);
 12304   vmessage (m, ap);
 12305   va_end (ap);
 12306 }
 12307 
 12308 
 12309 /* Display the current message in the current mini-buffer.  This is
 12310    only called from error handlers in process.c, and is not time
 12311    critical.  */
 12312 
 12313 void
 12314 update_echo_area (void)
 12315 {
 12316   if (!NILP (echo_area_buffer[0]))
 12317     {
 12318       Lisp_Object string;
 12319       string = Fcurrent_message ();
 12320       message3 (string);
 12321     }
 12322 }
 12323 
 12324 
 12325 /* Make sure echo area buffers in `echo_buffers' are live.
 12326    If they aren't, make new ones.  */
 12327 
 12328 static void
 12329 ensure_echo_area_buffers (void)
 12330 {
 12331   for (int i = 0; i < 2; i++)
 12332     if (!BUFFERP (echo_buffer[i])
 12333         || !BUFFER_LIVE_P (XBUFFER (echo_buffer[i])))
 12334       {
 12335         Lisp_Object old_buffer = echo_buffer[i];
 12336         static char const name_fmt[] = " *Echo Area %d*";
 12337         char name[sizeof name_fmt + INT_STRLEN_BOUND (int)];
 12338         AUTO_STRING_WITH_LEN (lname, name, sprintf (name, name_fmt, i));
 12339         echo_buffer[i] = Fget_buffer_create (lname, Qnil);
 12340         bset_truncate_lines (XBUFFER (echo_buffer[i]), Qnil);
 12341         /* to force word wrap in echo area -
 12342            it was decided to postpone this*/
 12343         /* XBUFFER (echo_buffer[i])->word_wrap = Qt; */
 12344 
 12345         for (int j = 0; j < 2; j++)
 12346           if (EQ (old_buffer, echo_area_buffer[j]))
 12347             echo_area_buffer[j] = echo_buffer[i];
 12348       }
 12349 }
 12350 
 12351 
 12352 /* Call FN with args A1..A2 with either the current or last displayed
 12353    echo_area_buffer as current buffer.
 12354 
 12355    WHICH zero means use the current message buffer
 12356    echo_area_buffer[0].  If that is nil, choose a suitable buffer
 12357    from echo_buffer[] and clear it.
 12358 
 12359    WHICH > 0 means use echo_area_buffer[1].  If that is nil, choose a
 12360    suitable buffer from echo_buffer[] and clear it.
 12361 
 12362    If WHICH < 0, set echo_area_buffer[1] to echo_area_buffer[0], so
 12363    that the current message becomes the last displayed one, choose a
 12364    suitable buffer for echo_area_buffer[0], and clear it.
 12365 
 12366    Value is what FN returns.  */
 12367 
 12368 static bool
 12369 with_echo_area_buffer (struct window *w, int which,
 12370                        bool (*fn) (void *, Lisp_Object),
 12371                        void *a1, Lisp_Object a2)
 12372 {
 12373   Lisp_Object buffer;
 12374   bool this_one, the_other, clear_buffer_p, rc;
 12375   specpdl_ref count = SPECPDL_INDEX ();
 12376 
 12377   /* If buffers aren't live, make new ones.  */
 12378   ensure_echo_area_buffers ();
 12379 
 12380   clear_buffer_p = false;
 12381 
 12382   if (which == 0)
 12383     this_one = false, the_other = true;
 12384   else if (which > 0)
 12385     this_one = true, the_other = false;
 12386   else
 12387     {
 12388       this_one = false, the_other = true;
 12389       clear_buffer_p = true;
 12390 
 12391       /* We need a fresh one in case the current echo buffer equals
 12392          the one containing the last displayed echo area message.  */
 12393       if (!NILP (echo_area_buffer[this_one])
 12394           && EQ (echo_area_buffer[this_one], echo_area_buffer[the_other]))
 12395         echo_area_buffer[this_one] = Qnil;
 12396     }
 12397 
 12398   /* Choose a suitable buffer from echo_buffer[] if we don't
 12399      have one.  */
 12400   if (NILP (echo_area_buffer[this_one]))
 12401     {
 12402       echo_area_buffer[this_one]
 12403         = (EQ (echo_area_buffer[the_other], echo_buffer[this_one])
 12404            ? echo_buffer[the_other]
 12405            : echo_buffer[this_one]);
 12406       clear_buffer_p = true;
 12407     }
 12408 
 12409   buffer = echo_area_buffer[this_one];
 12410 
 12411   /* Don't get confused by reusing the buffer used for echoing
 12412      for a different purpose.  */
 12413   if (echo_kboard == NULL && EQ (buffer, echo_message_buffer))
 12414     cancel_echoing ();
 12415 
 12416   record_unwind_protect (unwind_with_echo_area_buffer,
 12417                          with_echo_area_buffer_unwind_data (w));
 12418 
 12419   /* Make the echo area buffer current.  Note that for display
 12420      purposes, it is not necessary that the displayed window's buffer
 12421      == current_buffer, except for text property lookup.  So, let's
 12422      only set that buffer temporarily here without doing a full
 12423      Fset_window_buffer.  We must also change w->pointm, though,
 12424      because otherwise an assertions in unshow_buffer fails, and Emacs
 12425      aborts.  */
 12426   set_buffer_internal_1 (XBUFFER (buffer));
 12427   if (w)
 12428     {
 12429       wset_buffer (w, buffer);
 12430       set_marker_both (w->pointm, buffer, BEG, BEG_BYTE);
 12431       set_marker_both (w->old_pointm, buffer, BEG, BEG_BYTE);
 12432     }
 12433 
 12434   bset_undo_list (current_buffer, Qt);
 12435   bset_read_only (current_buffer, Qnil);
 12436   specbind (Qinhibit_read_only, Qt);
 12437   specbind (Qinhibit_modification_hooks, Qt);
 12438 
 12439   if (clear_buffer_p && Z > BEG)
 12440     del_range (BEG, Z);
 12441 
 12442   eassert (BEGV >= BEG);
 12443   eassert (ZV <= Z && ZV >= BEGV);
 12444 
 12445   rc = fn (a1, a2);
 12446 
 12447   eassert (BEGV >= BEG);
 12448   eassert (ZV <= Z && ZV >= BEGV);
 12449 
 12450   unbind_to (count, Qnil);
 12451   return rc;
 12452 }
 12453 
 12454 
 12455 /* Save state that should be preserved around the call to the function
 12456    FN called in with_echo_area_buffer.  */
 12457 
 12458 static Lisp_Object
 12459 with_echo_area_buffer_unwind_data (struct window *w)
 12460 {
 12461   int i = 0;
 12462   Lisp_Object vector, tmp;
 12463 
 12464   /* Reduce consing by keeping one vector in
 12465      Vwith_echo_area_save_vector.  */
 12466   vector = Vwith_echo_area_save_vector;
 12467   Vwith_echo_area_save_vector = Qnil;
 12468 
 12469   if (NILP (vector))
 12470     vector = make_nil_vector (11);
 12471 
 12472   XSETBUFFER (tmp, current_buffer); ASET (vector, i, tmp); ++i;
 12473   ASET (vector, i, Vdeactivate_mark); ++i;
 12474   ASET (vector, i, make_fixnum (windows_or_buffers_changed)); ++i;
 12475 
 12476   if (w)
 12477     {
 12478       XSETWINDOW (tmp, w); ASET (vector, i, tmp); ++i;
 12479       ASET (vector, i, w->contents); ++i;
 12480       ASET (vector, i, make_fixnum (marker_position (w->pointm))); ++i;
 12481       ASET (vector, i, make_fixnum (marker_byte_position (w->pointm))); ++i;
 12482       ASET (vector, i, make_fixnum (marker_position (w->old_pointm))); ++i;
 12483       ASET (vector, i, make_fixnum (marker_byte_position (w->old_pointm))); ++i;
 12484       ASET (vector, i, make_fixnum (marker_position (w->start))); ++i;
 12485       ASET (vector, i, make_fixnum (marker_byte_position (w->start))); ++i;
 12486     }
 12487   else
 12488     {
 12489       int end = i + 8;
 12490       for (; i < end; ++i)
 12491         ASET (vector, i, Qnil);
 12492     }
 12493 
 12494   eassert (i == ASIZE (vector));
 12495   return vector;
 12496 }
 12497 
 12498 
 12499 /* Restore global state from VECTOR which was created by
 12500    with_echo_area_buffer_unwind_data.  */
 12501 
 12502 static void
 12503 unwind_with_echo_area_buffer (Lisp_Object vector)
 12504 {
 12505   set_buffer_internal_1 (XBUFFER (AREF (vector, 0)));
 12506   Vdeactivate_mark = AREF (vector, 1);
 12507   windows_or_buffers_changed = XFIXNAT (AREF (vector, 2));
 12508 
 12509   if (WINDOWP (AREF (vector, 3)))
 12510     {
 12511       struct window *w;
 12512       Lisp_Object buffer;
 12513 
 12514       w = XWINDOW (AREF (vector, 3));
 12515       buffer = AREF (vector, 4);
 12516 
 12517       wset_buffer (w, buffer);
 12518       set_marker_restricted_both (w->pointm, buffer,
 12519                                   XFIXNAT (AREF (vector, 5)),
 12520                                   XFIXNAT (AREF (vector, 6)));
 12521       set_marker_restricted_both (w->old_pointm, buffer,
 12522                                   XFIXNAT (AREF (vector, 7)),
 12523                                   XFIXNAT (AREF (vector, 8)));
 12524       set_marker_restricted_both (w->start, buffer,
 12525                                   XFIXNAT (AREF (vector, 9)),
 12526                                   XFIXNAT (AREF (vector, 10)));
 12527     }
 12528 
 12529   Vwith_echo_area_save_vector = vector;
 12530 }
 12531 
 12532 
 12533 /* Set up the echo area for use by print functions.  MULTIBYTE_P
 12534    means we will print multibyte.  */
 12535 
 12536 void
 12537 setup_echo_area_for_printing (bool multibyte_p)
 12538 {
 12539   /* If we can't find an echo area any more, exit.  */
 12540   if (! FRAME_LIVE_P (XFRAME (selected_frame)))
 12541     Fkill_emacs (Qnil, Qnil);
 12542 
 12543   ensure_echo_area_buffers ();
 12544 
 12545   if (!message_buf_print)
 12546     {
 12547       /* A message has been output since the last time we printed.
 12548          Choose a fresh echo area buffer.  */
 12549       if (EQ (echo_area_buffer[1], echo_buffer[0]))
 12550         echo_area_buffer[0] = echo_buffer[1];
 12551       else
 12552         echo_area_buffer[0] = echo_buffer[0];
 12553 
 12554       /* Switch to that buffer and clear it.  */
 12555       set_buffer_internal (XBUFFER (echo_area_buffer[0]));
 12556       bset_truncate_lines (current_buffer, Qnil);
 12557 
 12558       if (Z > BEG)
 12559         {
 12560           specpdl_ref count = SPECPDL_INDEX ();
 12561           specbind (Qinhibit_read_only, Qt);
 12562           /* Note that undo recording is always disabled.  */
 12563           del_range (BEG, Z);
 12564           unbind_to (count, Qnil);
 12565         }
 12566       TEMP_SET_PT_BOTH (BEG, BEG_BYTE);
 12567 
 12568       /* Set up the buffer for the multibyteness we need.  We always
 12569          set it to be multibyte, except when
 12570          unibyte-display-via-language-environment is non-nil and the
 12571          buffer from which we are called is unibyte, because in that
 12572          case unibyte characters should not be displayed as octal
 12573          escapes.  */
 12574       if (unibyte_display_via_language_environment
 12575           && !multibyte_p
 12576           && !NILP (BVAR (current_buffer, enable_multibyte_characters)))
 12577         Fset_buffer_multibyte (Qnil);
 12578       else if (NILP (BVAR (current_buffer, enable_multibyte_characters)))
 12579         Fset_buffer_multibyte (Qt);
 12580 
 12581       /* Raise the frame containing the echo area.  */
 12582       if (minibuffer_auto_raise)
 12583         {
 12584           struct frame *sf = SELECTED_FRAME ();
 12585           Lisp_Object mini_window;
 12586           mini_window = FRAME_MINIBUF_WINDOW (sf);
 12587           Fraise_frame  (WINDOW_FRAME (XWINDOW (mini_window)));
 12588         }
 12589 
 12590       message_log_maybe_newline ();
 12591       message_buf_print = true;
 12592     }
 12593   else
 12594     {
 12595       if (NILP (echo_area_buffer[0]))
 12596         {
 12597           if (EQ (echo_area_buffer[1], echo_buffer[0]))
 12598             echo_area_buffer[0] = echo_buffer[1];
 12599           else
 12600             echo_area_buffer[0] = echo_buffer[0];
 12601         }
 12602 
 12603       if (current_buffer != XBUFFER (echo_area_buffer[0]))
 12604         {
 12605           /* Someone switched buffers between print requests.  */
 12606           set_buffer_internal (XBUFFER (echo_area_buffer[0]));
 12607           bset_truncate_lines (current_buffer, Qnil);
 12608         }
 12609     }
 12610 }
 12611 
 12612 
 12613 /* Display an echo area message in window W.  Value is true if W's
 12614    height is changed.  If display_last_displayed_message_p,
 12615    display the message that was last displayed, otherwise
 12616    display the current message.  */
 12617 
 12618 static bool
 12619 display_echo_area (struct window *w)
 12620 {
 12621   bool no_message_p, window_height_changed_p;
 12622 
 12623   /* Temporarily disable garbage collections while displaying the echo
 12624      area.  This is done because a GC can print a message itself.
 12625      That message would modify the echo area buffer's contents while a
 12626      redisplay of the buffer is going on, and seriously confuse
 12627      redisplay.  */
 12628   specpdl_ref count = inhibit_garbage_collection ();
 12629 
 12630   /* If there is no message, we must call display_echo_area_1
 12631      nevertheless because it resizes the window.  But we will have to
 12632      reset the echo_area_buffer in question to nil at the end because
 12633      with_echo_area_buffer will set it to an empty buffer.  */
 12634   bool i = display_last_displayed_message_p;
 12635   /* According to the C standard, the integral value
 12636      of a "bool" is always 0 or 1, so this array access is safe here,
 12637      if oddly typed. */
 12638   no_message_p = NILP (echo_area_buffer[i]);
 12639 
 12640   window_height_changed_p
 12641     = with_echo_area_buffer (w, display_last_displayed_message_p,
 12642                              display_echo_area_1, w, Qnil);
 12643 
 12644   if (no_message_p)
 12645     echo_area_buffer[i] = Qnil;
 12646 
 12647   unbind_to (count, Qnil);
 12648   return window_height_changed_p;
 12649 }
 12650 
 12651 
 12652 /* Helper for display_echo_area.  Display the current buffer which
 12653    contains the current echo area message in window W, a mini-window,
 12654    a pointer to which is passed in A1.  A2 is currently not used.
 12655    Change the height of W so that all of the message is displayed.
 12656    Value is true if height of W was changed.  */
 12657 
 12658 static bool
 12659 display_echo_area_1 (void *a1, Lisp_Object a2)
 12660 {
 12661   struct window *w = a1;
 12662   Lisp_Object window;
 12663   struct text_pos start;
 12664 
 12665   /* We are about to enter redisplay without going through
 12666      redisplay_internal, so we need to forget these faces by hand
 12667      here.  */
 12668   forget_escape_and_glyphless_faces ();
 12669 
 12670   /* Do this before displaying, so that we have a large enough glyph
 12671      matrix for the display.  If we can't get enough space for the
 12672      whole text, display the last N lines.  That works by setting w->start.  */
 12673   bool window_height_changed_p = resize_mini_window (w, false);
 12674 
 12675   /* Use the starting position chosen by resize_mini_window.  */
 12676   SET_TEXT_POS_FROM_MARKER (start, w->start);
 12677 
 12678   /* Display.  */
 12679   clear_glyph_matrix (w->desired_matrix);
 12680   XSETWINDOW (window, w);
 12681   void *itdata = bidi_shelve_cache ();
 12682   try_window (window, start, 0);
 12683   bidi_unshelve_cache (itdata, false);
 12684 
 12685   return window_height_changed_p;
 12686 }
 12687 
 12688 
 12689 /* Resize the echo area window to exactly the size needed for the
 12690    currently displayed message, if there is one.  If a mini-buffer
 12691    is active, don't shrink it.  */
 12692 
 12693 void
 12694 resize_echo_area_exactly (void)
 12695 {
 12696   if (BUFFERP (echo_area_buffer[0])
 12697       && WINDOWP (echo_area_window))
 12698     {
 12699       struct window *w = XWINDOW (echo_area_window);
 12700       Lisp_Object resize_exactly = (minibuf_level == 0 ? Qt : Qnil);
 12701       bool resized_p = with_echo_area_buffer (w, 0, resize_mini_window_1,
 12702                                               w, resize_exactly);
 12703       if (resized_p)
 12704         {
 12705           windows_or_buffers_changed = 42;
 12706           update_mode_lines = 30;
 12707           redisplay_internal ();
 12708         }
 12709     }
 12710 }
 12711 
 12712 
 12713 /* Callback function for with_echo_area_buffer, when used from
 12714    resize_echo_area_exactly.  A1 contains a pointer to the window to
 12715    resize, EXACTLY non-nil means resize the mini-window exactly to the
 12716    size of the text displayed.  Value is what resize_mini_window
 12717    returns.  */
 12718 
 12719 static bool
 12720 resize_mini_window_1 (void *a1, Lisp_Object exactly)
 12721 {
 12722   return resize_mini_window (a1, !NILP (exactly));
 12723 }
 12724 
 12725 
 12726 /* Resize mini-window W to fit the size of its contents.  EXACT_P
 12727    means size the window exactly to the size needed.  Otherwise, it's
 12728    only enlarged until W's buffer is empty.
 12729 
 12730    Set W->start to the right place to begin display.  If the whole
 12731    contents fit, start at the beginning.  Otherwise, start so as
 12732    to make the end of the contents appear.  This is particularly
 12733    important for y-or-n-p, but seems desirable generally.
 12734 
 12735    Value is true if the window height has been changed.  */
 12736 
 12737 bool
 12738 resize_mini_window (struct window *w, bool exact_p)
 12739 {
 12740   struct frame *f = XFRAME (w->frame);
 12741   int old_height = WINDOW_BOX_TEXT_HEIGHT (w);
 12742 
 12743   eassert (MINI_WINDOW_P (w));
 12744 
 12745   /* Don't resize windows while redisplaying a window; it would
 12746      confuse redisplay functions when the size of the window they are
 12747      displaying changes from under them.  Such a resizing can happen,
 12748      for instance, when which-func prints a long message while
 12749      we are running fontification-functions.  We're running these
 12750      functions with safe_call which binds inhibit-redisplay to t.  */
 12751   if (!NILP (Vinhibit_redisplay))
 12752     return false;
 12753 
 12754   /* By default, start display at the beginning.  */
 12755   if (redisplay_adhoc_scroll_in_resize_mini_windows)
 12756     set_marker_both (w->start, w->contents,
 12757                      BUF_BEGV (XBUFFER (w->contents)),
 12758                      BUF_BEGV_BYTE (XBUFFER (w->contents)));
 12759 
 12760   /* Nil means don't try to resize.  */
 12761   if ((NILP (Vresize_mini_windows)
 12762        && (NILP (resize_mini_frames) || !FRAME_MINIBUF_ONLY_P (f)))
 12763       || (FRAME_X_P (f) && FRAME_OUTPUT_DATA (f) == NULL))
 12764     return false;
 12765 
 12766   if (FRAME_MINIBUF_ONLY_P (f))
 12767     {
 12768       if (!NILP (resize_mini_frames))
 12769         safe_call1 (Qwindow__resize_mini_frame, WINDOW_FRAME (w));
 12770     }
 12771   else
 12772     {
 12773       struct it it;
 12774       int unit = FRAME_LINE_HEIGHT (f);
 12775       int height, max_height;
 12776       struct text_pos start;
 12777       struct buffer *old_current_buffer = NULL;
 12778       int windows_height = FRAME_INNER_HEIGHT (f);
 12779 
 12780       if (current_buffer != XBUFFER (w->contents))
 12781         {
 12782           old_current_buffer = current_buffer;
 12783           set_buffer_internal (XBUFFER (w->contents));
 12784         }
 12785 
 12786       init_iterator (&it, w, BEGV, BEGV_BYTE, NULL, DEFAULT_FACE_ID);
 12787 
 12788       /* Compute the max. number of lines specified by the user.  */
 12789       if (FLOATP (Vmax_mini_window_height))
 12790         max_height = XFLOAT_DATA (Vmax_mini_window_height) * windows_height;
 12791       else if (FIXNUMP (Vmax_mini_window_height))
 12792         max_height = XFIXNUM (Vmax_mini_window_height) * unit;
 12793       else
 12794         max_height = windows_height / 4;
 12795 
 12796       /* Correct that max. height if it's bogus.  */
 12797       max_height = clip_to_bounds (unit, max_height, windows_height);
 12798 
 12799       /* Find out the height of the text in the window.  */
 12800       last_height = 0;
 12801       move_it_to (&it, ZV, -1, -1, -1, MOVE_TO_POS);
 12802       /* If move_it_to moved to the next visible line after EOB,
 12803          account for the height of the last full line.  */
 12804       if (it.max_ascent == 0 && it.max_descent == 0)
 12805         {
 12806           height = it.current_y;
 12807           /* Don't add the last line's height if lines are truncated
 12808              and the text doesn't end in a newline.
 12809              FIXME: if the text ends in a newline from a display
 12810              property or an overlay string, they lose: the mini-window
 12811              might not show the last empty line.  */
 12812           if (!(it.line_wrap == TRUNCATE
 12813                 && it.current_x <= it.first_visible_x
 12814                 && ZV_BYTE > 1
 12815                 && FETCH_BYTE (ZV_BYTE - 1) != '\n'))
 12816             height += last_height;
 12817         }
 12818       else
 12819         height = it.current_y + it.max_ascent + it.max_descent;
 12820       height -= min (it.extra_line_spacing, it.max_extra_line_spacing);
 12821 
 12822       /* Compute a suitable window start.  */
 12823       if (height > max_height)
 12824         {
 12825           height = (max_height / unit) * unit;
 12826           if (redisplay_adhoc_scroll_in_resize_mini_windows)
 12827             {
 12828               init_iterator (&it, w, ZV, ZV_BYTE, NULL, DEFAULT_FACE_ID);
 12829               move_it_vertically_backward (&it, height - unit);
 12830               /* The following move is usually a no-op when the stuff
 12831                  displayed in the mini-window comes entirely from buffer
 12832                  text, but it is needed when some of it comes from overlay
 12833                  strings, especially when there's an after-string at ZV.
 12834                  This happens with some completion packages, like
 12835                  icomplete, ido-vertical, etc.  With those packages, if we
 12836                  don't force w->start to be at the beginning of a screen
 12837                  line, important parts of the stuff in the mini-window,
 12838                  such as user prompt, will be hidden from view.  */
 12839               move_it_by_lines (&it, 0);
 12840               start = it.current.pos;
 12841               /* Prevent redisplay_window from recentering, and thus from
 12842                  overriding the window-start point we computed here.  */
 12843               w->start_at_line_beg = false;
 12844               SET_MARKER_FROM_TEXT_POS (w->start, start);
 12845             }
 12846         }
 12847       else
 12848         {
 12849           SET_TEXT_POS (start, BEGV, BEGV_BYTE);
 12850           SET_MARKER_FROM_TEXT_POS (w->start, start);
 12851         }
 12852 
 12853       if (EQ (Vresize_mini_windows, Qgrow_only))
 12854         {
 12855           /* Let it grow only, until we display an empty message, in which
 12856              case the window shrinks again.  */
 12857           if (height > old_height)
 12858             grow_mini_window (w, height - old_height);
 12859           else if (height < old_height && (exact_p || BEGV == ZV))
 12860             shrink_mini_window (w);
 12861         }
 12862       else if (height != old_height)
 12863         /* Always resize to exact size needed.  */
 12864         grow_mini_window (w, height - old_height);
 12865 
 12866       if (old_current_buffer)
 12867         set_buffer_internal (old_current_buffer);
 12868     }
 12869 
 12870   return WINDOW_BOX_TEXT_HEIGHT (w) != old_height;
 12871 }
 12872 
 12873 
 12874 /* Value is the current message, a string, or nil if there is no
 12875    current message.  */
 12876 
 12877 Lisp_Object
 12878 current_message (void)
 12879 {
 12880   Lisp_Object msg;
 12881 
 12882   if (!BUFFERP (echo_area_buffer[0]))
 12883     msg = Qnil;
 12884   else
 12885     {
 12886       with_echo_area_buffer (0, 0, current_message_1, &msg, Qnil);
 12887       if (NILP (msg))
 12888         echo_area_buffer[0] = Qnil;
 12889     }
 12890 
 12891   return msg;
 12892 }
 12893 
 12894 
 12895 static bool
 12896 current_message_1 (void *a1, Lisp_Object a2)
 12897 {
 12898   Lisp_Object *msg = a1;
 12899 
 12900   if (Z > BEG)
 12901     *msg = make_buffer_string (BEG, Z, true);
 12902   else
 12903     *msg = Qnil;
 12904   return false;
 12905 }
 12906 
 12907 
 12908 /* Push the current message on Vmessage_stack for later restoration
 12909    by restore_message.  Value is true if the current message isn't
 12910    empty.  This is a relatively infrequent operation, so it's not
 12911    worth optimizing.  */
 12912 
 12913 bool
 12914 push_message (void)
 12915 {
 12916   Lisp_Object msg = current_message ();
 12917   Vmessage_stack = Fcons (msg, Vmessage_stack);
 12918   return STRINGP (msg);
 12919 }
 12920 
 12921 
 12922 /* Restore message display from the top of Vmessage_stack.  */
 12923 
 12924 void
 12925 restore_message (void)
 12926 {
 12927   eassert (CONSP (Vmessage_stack));
 12928   message3_nolog (XCAR (Vmessage_stack));
 12929 }
 12930 
 12931 
 12932 /* Handler for unwind-protect calling pop_message.  */
 12933 
 12934 void
 12935 pop_message_unwind (void)
 12936 {
 12937   /* Pop the top-most entry off Vmessage_stack.  */
 12938   eassert (CONSP (Vmessage_stack));
 12939   Vmessage_stack = XCDR (Vmessage_stack);
 12940 }
 12941 
 12942 
 12943 /* Check that Vmessage_stack is nil.  Called from emacs.c when Emacs
 12944    exits.  If the stack is not empty, we have a missing
 12945    pop_message_unwind somewhere.  */
 12946 
 12947 void
 12948 check_message_stack (void)
 12949 {
 12950   if (!NILP (Vmessage_stack))
 12951     emacs_abort ();
 12952 }
 12953 
 12954 void
 12955 clear_message_stack (void)
 12956 {
 12957   Vmessage_stack = Qnil;
 12958 }
 12959 
 12960 /* Truncate to NCHARS what will be displayed in the echo area the next
 12961    time we display it---but don't redisplay it now.  */
 12962 
 12963 void
 12964 truncate_echo_area (ptrdiff_t nchars)
 12965 {
 12966   if (nchars == 0)
 12967     echo_area_buffer[0] = Qnil;
 12968   else if (!noninteractive
 12969            && INTERACTIVE
 12970            && !NILP (echo_area_buffer[0]))
 12971     {
 12972       struct frame *sf = SELECTED_FRAME ();
 12973       /* Error messages get reported properly by cmd_error, so this must be
 12974          just an informative message; if the frame hasn't really been
 12975          initialized yet, just toss it.  */
 12976       if (sf->glyphs_initialized_p)
 12977         with_echo_area_buffer (0, 0, truncate_message_1,
 12978                                (void *) (intptr_t) nchars, Qnil);
 12979     }
 12980 }
 12981 
 12982 
 12983 /* Helper function for truncate_echo_area.  Truncate the current
 12984    message to at most NCHARS characters.  */
 12985 
 12986 static bool
 12987 truncate_message_1 (void *a1, Lisp_Object a2)
 12988 {
 12989   intptr_t nchars = (intptr_t) a1;
 12990   if (BEG + nchars < Z)
 12991     del_range (BEG + nchars, Z);
 12992   if (Z == BEG)
 12993     echo_area_buffer[0] = Qnil;
 12994   return false;
 12995 }
 12996 
 12997 extern intptr_t garbage_collection_inhibited;
 12998 
 12999 /* Set the current message to STRING.  */
 13000 
 13001 static void
 13002 set_message (Lisp_Object string)
 13003 {
 13004   Lisp_Object message = Qnil;
 13005 
 13006   eassert (STRINGP (string));
 13007 
 13008   if (FUNCTIONP (Vset_message_function)
 13009       /* FIXME: (bug#63253) We should really make the regexp engine re-entrant,
 13010          but in the mean time, let's ignore `set-message-function` when
 13011          called from `probably_quit`.  */
 13012       && !garbage_collection_inhibited)
 13013     {
 13014       specpdl_ref count = SPECPDL_INDEX ();
 13015       specbind (Qinhibit_quit, Qt);
 13016       message = safe_call1 (Vset_message_function, string);
 13017       unbind_to (count, Qnil);
 13018 
 13019       if (STRINGP (message))
 13020         {
 13021           string = message;
 13022           message = Qnil;
 13023         }
 13024     }
 13025 
 13026   if (NILP (message))
 13027     {
 13028       message_enable_multibyte = STRING_MULTIBYTE (string);
 13029 
 13030       with_echo_area_buffer (0, -1, set_message_1, 0, string);
 13031       message_buf_print = false;
 13032       help_echo_showing_p = false;
 13033     }
 13034 
 13035   if (STRINGP (Vdebug_on_message)
 13036       && STRINGP (string)
 13037       && fast_string_match (Vdebug_on_message, string) >= 0)
 13038     call_debugger (list2 (Qerror, string));
 13039 }
 13040 
 13041 
 13042 /* Helper function for set_message.  First argument is ignored and second
 13043    argument has the same meaning as for set_message.
 13044    This function is called with the echo area buffer being current.  */
 13045 
 13046 static bool
 13047 set_message_1 (void *a1, Lisp_Object string)
 13048 {
 13049   eassert (STRINGP (string));
 13050 
 13051   /* Change multibyteness of the echo buffer appropriately.  We always
 13052      set it to be multibyte, except when
 13053      unibyte-display-via-language-environment is non-nil and the
 13054      string to display is unibyte, because in that case unibyte
 13055      characters should not be displayed as octal escapes.  */
 13056   if (!message_enable_multibyte
 13057       && unibyte_display_via_language_environment
 13058       && !NILP (BVAR (current_buffer, enable_multibyte_characters)))
 13059     Fset_buffer_multibyte (Qnil);
 13060   else if (NILP (BVAR (current_buffer, enable_multibyte_characters)))
 13061     Fset_buffer_multibyte (Qt);
 13062 
 13063   bset_truncate_lines (current_buffer, message_truncate_lines ? Qt : Qnil);
 13064   if (!NILP (BVAR (current_buffer, bidi_display_reordering)))
 13065     bset_bidi_paragraph_direction (current_buffer, Qleft_to_right);
 13066 
 13067   /* Insert new message at BEG.  */
 13068   TEMP_SET_PT_BOTH (BEG, BEG_BYTE);
 13069 
 13070   /* This function takes care of single/multibyte conversion.
 13071      We just have to ensure that the echo area buffer has the right
 13072      setting of enable_multibyte_characters.  */
 13073   insert_from_string (string, 0, 0, SCHARS (string), SBYTES (string), true);
 13074 
 13075   return false;
 13076 }
 13077 
 13078 
 13079 /* Clear messages.  CURRENT_P means clear the current message.
 13080    LAST_DISPLAYED_P means clear the message last displayed.  */
 13081 
 13082 void
 13083 clear_message (bool current_p, bool last_displayed_p)
 13084 {
 13085   Lisp_Object preserve = Qnil;
 13086 
 13087   if (current_p)
 13088     {
 13089       if (FUNCTIONP (Vclear_message_function)
 13090           /* FIXME: (bug#63253) Same as for `set-message-function` above.  */
 13091           && !garbage_collection_inhibited)
 13092         {
 13093           specpdl_ref count = SPECPDL_INDEX ();
 13094           specbind (Qinhibit_quit, Qt);
 13095           preserve = safe_call (1, Vclear_message_function);
 13096           unbind_to (count, Qnil);
 13097         }
 13098 
 13099       if (!EQ (preserve, Qdont_clear_message))
 13100         {
 13101           echo_area_buffer[0] = Qnil;
 13102           message_cleared_p = true;
 13103         }
 13104     }
 13105 
 13106   if (last_displayed_p)
 13107     echo_area_buffer[1] = Qnil;
 13108 
 13109   message_buf_print = false;
 13110 }
 13111 
 13112 /* Clear garbaged frames.
 13113 
 13114    This function is used where the old redisplay called
 13115    redraw_garbaged_frames which in turn called redraw_frame which in
 13116    turn called clear_frame.  The call to clear_frame was a source of
 13117    flickering.  I believe a clear_frame is not necessary.  It should
 13118    suffice in the new redisplay to invalidate all current matrices,
 13119    and ensure a complete redisplay of all windows.  */
 13120 
 13121 static void
 13122 clear_garbaged_frames (void)
 13123 {
 13124   if (frame_garbaged)
 13125     {
 13126       Lisp_Object tail, frame;
 13127       struct frame *sf = SELECTED_FRAME ();
 13128 
 13129       FOR_EACH_FRAME (tail, frame)
 13130         {
 13131           struct frame *f = XFRAME (frame);
 13132 
 13133           if (FRAME_REDISPLAY_P (f) && FRAME_GARBAGED_P (f))
 13134             {
 13135               if (f->resized_p
 13136                   /* It makes no sense to redraw a non-selected TTY
 13137                      frame, since that will actually clear the
 13138                      selected frame, and might leave the selected
 13139                      frame with corrupted display, if it happens not
 13140                      to be marked garbaged.  */
 13141                   && !(f != sf && (FRAME_TERMCAP_P (f) || FRAME_MSDOS_P (f))))
 13142                 redraw_frame (f);
 13143               else
 13144                 clear_current_matrices (f);
 13145 
 13146 #ifdef HAVE_WINDOW_SYSTEM
 13147               if (FRAME_WINDOW_P (f)
 13148                   && FRAME_RIF (f)->clear_under_internal_border)
 13149                 FRAME_RIF (f)->clear_under_internal_border (f);
 13150 #endif
 13151               fset_redisplay (f);
 13152               f->garbaged = false;
 13153               f->resized_p = false;
 13154             }
 13155         }
 13156 
 13157       frame_garbaged = false;
 13158     }
 13159 }
 13160 
 13161 
 13162 /* Redisplay the echo area of the selected frame.  If UPDATE_FRAME_P, update
 13163    selected_frame.  */
 13164 
 13165 static void
 13166 echo_area_display (bool update_frame_p)
 13167 {
 13168   Lisp_Object mini_window;
 13169   struct window *w;
 13170   struct frame *f;
 13171   bool window_height_changed_p = false;
 13172   struct frame *sf = SELECTED_FRAME ();
 13173 
 13174   mini_window = FRAME_MINIBUF_WINDOW (sf);
 13175   if (NILP (mini_window))
 13176     return;
 13177 
 13178   w = XWINDOW (mini_window);
 13179   f = XFRAME (WINDOW_FRAME (w));
 13180 
 13181   /* Don't display if frame is invisible or not yet initialized.  */
 13182   if (!FRAME_REDISPLAY_P (f) || !f->glyphs_initialized_p)
 13183     return;
 13184 
 13185 #ifdef HAVE_WINDOW_SYSTEM
 13186   /* When Emacs starts, selected_frame may be the initial terminal
 13187      frame.  If we let this through, a message would be displayed on
 13188      the terminal.  */
 13189   if (FRAME_INITIAL_P (XFRAME (selected_frame)))
 13190     return;
 13191 #endif /* HAVE_WINDOW_SYSTEM */
 13192 
 13193   /* Redraw garbaged frames.  */
 13194   clear_garbaged_frames ();
 13195 
 13196   if (!NILP (echo_area_buffer[0]) || minibuf_level == 0)
 13197     {
 13198       echo_area_window = mini_window;
 13199       window_height_changed_p = display_echo_area (w);
 13200       w->must_be_updated_p = true;
 13201 
 13202       /* Update the display, unless called from redisplay_internal.
 13203          Also don't update the screen during redisplay itself.  The
 13204          update will happen at the end of redisplay, and an update
 13205          here could cause confusion.  */
 13206       if (update_frame_p && !redisplaying_p)
 13207         {
 13208           int n = 0;
 13209 
 13210           /* If the display update has been interrupted by pending
 13211              input, update mode lines in the frame.  Due to the
 13212              pending input, it might have been that redisplay hasn't
 13213              been called, so that mode lines above the echo area are
 13214              garbaged.  This looks odd, so we prevent it here.  */
 13215           if (!display_completed)
 13216             {
 13217               n = redisplay_mode_lines (FRAME_ROOT_WINDOW (f), false);
 13218 
 13219 #ifdef HAVE_WINDOW_SYSTEM
 13220               if (FRAME_WINDOW_P (f)
 13221                   && FRAME_RIF (f)->clear_under_internal_border)
 13222                 FRAME_RIF (f)->clear_under_internal_border (f);
 13223 #endif
 13224             }
 13225 
 13226           if (window_height_changed_p
 13227               /* Don't do this if Emacs is shutting down.  Redisplay
 13228                  needs to run hooks.  */
 13229               && !NILP (Vrun_hooks))
 13230             {
 13231               /* Must update other windows.  Likewise as in other
 13232                  cases, don't let this update be interrupted by
 13233                  pending input.  */
 13234               specpdl_ref count = SPECPDL_INDEX ();
 13235               specbind (Qredisplay_dont_pause, Qt);
 13236               fset_redisplay (f);
 13237               redisplay_internal ();
 13238               unbind_to (count, Qnil);
 13239             }
 13240           else if (FRAME_WINDOW_P (f) && n == 0)
 13241             {
 13242               /* Window configuration is the same as before.
 13243                  Can do with a display update of the echo area,
 13244                  unless we displayed some mode lines.  */
 13245               update_single_window (w);
 13246               flush_frame (f);
 13247             }
 13248           else
 13249             update_frame (f, true, true);
 13250 
 13251           /* If cursor is in the echo area, make sure that the next
 13252              redisplay displays the minibuffer, so that the cursor will
 13253              be replaced with what the minibuffer wants.  */
 13254           if (cursor_in_echo_area)
 13255             wset_redisplay (XWINDOW (mini_window));
 13256         }
 13257     }
 13258   else if (!EQ (mini_window, selected_window))
 13259     wset_redisplay (XWINDOW (mini_window));
 13260 
 13261   /* Last displayed message is now the current message.  */
 13262   echo_area_buffer[1] = echo_area_buffer[0];
 13263   /* Inform read_char that we're not echoing.  */
 13264   echo_message_buffer = Qnil;
 13265 
 13266   /* Prevent redisplay optimization in redisplay_internal by resetting
 13267      this_line_start_pos.  This is done because the mini-buffer now
 13268      displays the message instead of its buffer text.  */
 13269   if (EQ (mini_window, selected_window))
 13270     CHARPOS (this_line_start_pos) = 0;
 13271 
 13272   if (window_height_changed_p)
 13273     {
 13274       fset_redisplay (f);
 13275 
 13276       /* If window configuration was changed, frames may have been
 13277          marked garbaged.  Clear them or we will experience
 13278          surprises wrt scrolling.
 13279          FIXME: How/why/when?  */
 13280       clear_garbaged_frames ();
 13281     }
 13282 }
 13283 
 13284 /* True if W's buffer was changed but not saved.  */
 13285 
 13286 static bool
 13287 window_buffer_changed (struct window *w)
 13288 {
 13289   struct buffer *b = XBUFFER (w->contents);
 13290 
 13291   eassert (BUFFER_LIVE_P (b));
 13292 
 13293   return (BUF_SAVE_MODIFF (b) < BUF_MODIFF (b)) != w->last_had_star;
 13294 }
 13295 
 13296 /* True if W has %c or %C in its mode line and mode line should be updated.  */
 13297 
 13298 static bool
 13299 mode_line_update_needed (struct window *w)
 13300 {
 13301   return (w->column_number_displayed != -1
 13302           && !(PT == w->last_point && !window_outdated (w))
 13303           && (w->column_number_displayed != current_column ()));
 13304 }
 13305 
 13306 /* True if window start of W is frozen and may not be changed during
 13307    redisplay.  */
 13308 
 13309 static bool
 13310 window_frozen_p (struct window *w)
 13311 {
 13312   if (FRAME_WINDOWS_FROZEN (XFRAME (WINDOW_FRAME (w))))
 13313     {
 13314       Lisp_Object window;
 13315 
 13316       XSETWINDOW (window, w);
 13317       if (MINI_WINDOW_P (w))
 13318         return false;
 13319       else if (EQ (window, selected_window))
 13320         return false;
 13321       else if (MINI_WINDOW_P (XWINDOW (selected_window))
 13322                && EQ (window, Vminibuf_scroll_window))
 13323         /* This special window can't be frozen too.  */
 13324         return false;
 13325       else
 13326         return true;
 13327     }
 13328   return false;
 13329 }
 13330 
 13331 /***********************************************************************
 13332                      Mode Lines and Frame Titles
 13333  ***********************************************************************/
 13334 
 13335 /* A buffer for constructing non-propertized mode-line strings and
 13336    frame titles in it; allocated from the heap in init_xdisp and
 13337    resized as needed in store_mode_line_noprop_char.  */
 13338 
 13339 static char *mode_line_noprop_buf;
 13340 
 13341 /* The buffer's end, and a current output position in it.  */
 13342 
 13343 static char *mode_line_noprop_buf_end;
 13344 static char *mode_line_noprop_ptr;
 13345 
 13346 #define MODE_LINE_NOPROP_LEN(start) \
 13347   ((mode_line_noprop_ptr - mode_line_noprop_buf) - start)
 13348 
 13349 static enum {
 13350   MODE_LINE_DISPLAY = 0,
 13351   MODE_LINE_TITLE,
 13352   MODE_LINE_NOPROP,
 13353   MODE_LINE_STRING
 13354 } mode_line_target;
 13355 
 13356 /* Alist that caches the results of :propertize.
 13357    Each element is (PROPERTIZED-STRING . PROPERTY-LIST).  */
 13358 static Lisp_Object mode_line_proptrans_alist;
 13359 
 13360 /* List of strings making up the mode-line.  */
 13361 static Lisp_Object mode_line_string_list;
 13362 
 13363 /* Base face property when building propertized mode line string.  */
 13364 static Lisp_Object mode_line_string_face;
 13365 static Lisp_Object mode_line_string_face_prop;
 13366 
 13367 
 13368 /* Unwind data for mode line strings */
 13369 
 13370 static Lisp_Object Vmode_line_unwind_vector;
 13371 
 13372 static Lisp_Object
 13373 format_mode_line_unwind_data (struct frame *target_frame,
 13374                               struct buffer *obuf,
 13375                               Lisp_Object owin,
 13376                               bool save_proptrans)
 13377 {
 13378   Lisp_Object vector, tmp;
 13379 
 13380   /* Reduce consing by keeping one vector in
 13381      Vwith_echo_area_save_vector.  */
 13382   vector = Vmode_line_unwind_vector;
 13383   Vmode_line_unwind_vector = Qnil;
 13384 
 13385   if (NILP (vector))
 13386     vector = make_nil_vector (12);
 13387 
 13388   ASET (vector, 0, make_fixnum (mode_line_target));
 13389   ASET (vector, 1, make_fixnum (MODE_LINE_NOPROP_LEN (0)));
 13390   ASET (vector, 2, mode_line_string_list);
 13391   ASET (vector, 3, save_proptrans ? mode_line_proptrans_alist : Qt);
 13392   ASET (vector, 4, mode_line_string_face);
 13393   ASET (vector, 5, mode_line_string_face_prop);
 13394 
 13395   if (obuf)
 13396     XSETBUFFER (tmp, obuf);
 13397   else
 13398     tmp = Qnil;
 13399   ASET (vector, 6, tmp);
 13400   ASET (vector, 7, owin);
 13401   if (target_frame)
 13402     {
 13403       Lisp_Object buffer = XWINDOW (target_frame->selected_window)->contents;
 13404       struct buffer *b = XBUFFER (buffer);
 13405       struct buffer *cb = current_buffer;
 13406 
 13407       /* Similarly to `with-selected-window', if the operation selects
 13408          a window on another frame, we must restore that frame's
 13409          selected window, and (for a tty) the top-frame.  */
 13410       ASET (vector, 8, target_frame->selected_window);
 13411       if (FRAME_TERMCAP_P (target_frame))
 13412         ASET (vector, 9, FRAME_TTY (target_frame)->top_frame);
 13413 
 13414       /* If we select a window on another frame, make sure that that
 13415          selection does not leave its buffer's point modified when
 13416          unwinding (Bug#32777).  */
 13417       ASET (vector, 10, buffer);
 13418       current_buffer = b;
 13419       ASET (vector, 11, build_marker (current_buffer, PT, PT_BYTE));
 13420       current_buffer = cb;
 13421     }
 13422 
 13423   return vector;
 13424 }
 13425 
 13426 static void
 13427 unwind_format_mode_line (Lisp_Object vector)
 13428 {
 13429   Lisp_Object old_window = AREF (vector, 7);
 13430   Lisp_Object target_frame_window = AREF (vector, 8);
 13431   Lisp_Object old_top_frame = AREF (vector, 9);
 13432 
 13433   mode_line_target = XFIXNUM (AREF (vector, 0));
 13434   mode_line_noprop_ptr = mode_line_noprop_buf + XFIXNUM (AREF (vector, 1));
 13435   mode_line_string_list = AREF (vector, 2);
 13436   if (! EQ (AREF (vector, 3), Qt))
 13437     mode_line_proptrans_alist = AREF (vector, 3);
 13438   mode_line_string_face = AREF (vector, 4);
 13439   mode_line_string_face_prop = AREF (vector, 5);
 13440 
 13441   /* Select window before buffer, since it may change the buffer.  */
 13442   if (WINDOW_LIVE_P (old_window))
 13443     {
 13444       /* If the operation that we are unwinding had selected a window
 13445          on a different frame, reset its frame-selected-window.  For a
 13446          text terminal, reset its top-frame if necessary.  */
 13447       if (WINDOW_LIVE_P (target_frame_window))
 13448         {
 13449           Lisp_Object frame
 13450             = WINDOW_FRAME (XWINDOW (target_frame_window));
 13451 
 13452           if (!EQ (frame, WINDOW_FRAME (XWINDOW (old_window))))
 13453             Fselect_window (target_frame_window, Qt);
 13454 
 13455           if (!NILP (old_top_frame) && !EQ (old_top_frame, frame)
 13456               /* This could've been destroyed during the formatting,
 13457                  possibly because the terminal was deleted.  */
 13458               && FRAME_LIVE_P (XFRAME (old_top_frame)))
 13459             Fselect_frame (old_top_frame, Qt);
 13460         }
 13461 
 13462       Fselect_window (old_window, Qt);
 13463 
 13464       /* Restore point of target_frame_window's buffer (Bug#32777).
 13465          But do this only after old_window has been reselected to
 13466          avoid that the window point of target_frame_window moves.  */
 13467       if (WINDOW_LIVE_P (target_frame_window))
 13468         {
 13469           Lisp_Object buffer = AREF (vector, 10);
 13470 
 13471           if (BUFFER_LIVE_P (XBUFFER (buffer)))
 13472             {
 13473               struct buffer *cb = current_buffer;
 13474 
 13475               current_buffer = XBUFFER (buffer);
 13476               set_point_from_marker (AREF (vector, 11));
 13477               ASET (vector, 11, Qnil);
 13478               current_buffer = cb;
 13479             }
 13480         }
 13481     }
 13482 
 13483   if (!NILP (AREF (vector, 6)))
 13484     {
 13485       set_buffer_internal_1 (XBUFFER (AREF (vector, 6)));
 13486       ASET (vector, 6, Qnil);
 13487     }
 13488 
 13489   Vmode_line_unwind_vector = vector;
 13490 }
 13491 
 13492 
 13493 /* Store a single character C for the frame title in mode_line_noprop_buf.
 13494    Re-allocate mode_line_noprop_buf if necessary.  */
 13495 
 13496 static void
 13497 store_mode_line_noprop_char (char c)
 13498 {
 13499   /* If output position has reached the end of the allocated buffer,
 13500      increase the buffer's size.  */
 13501   if (mode_line_noprop_ptr == mode_line_noprop_buf_end)
 13502     {
 13503       ptrdiff_t len = MODE_LINE_NOPROP_LEN (0);
 13504       ptrdiff_t size = len;
 13505       mode_line_noprop_buf =
 13506         xpalloc (mode_line_noprop_buf, &size, 1, STRING_BYTES_BOUND, 1);
 13507       mode_line_noprop_buf_end = mode_line_noprop_buf + size;
 13508       mode_line_noprop_ptr = mode_line_noprop_buf + len;
 13509     }
 13510 
 13511   *mode_line_noprop_ptr++ = c;
 13512 }
 13513 
 13514 
 13515 /* Store part of a frame title in mode_line_noprop_buf, beginning at
 13516    mode_line_noprop_ptr.  STRING is the string to store.  Do not copy
 13517    characters that yield more columns than PRECISION; PRECISION <= 0
 13518    means copy the whole string.  Pad with spaces until FIELD_WIDTH
 13519    number of characters have been copied; FIELD_WIDTH <= 0 means don't
 13520    pad.  Called from display_mode_element when it is used to build a
 13521    frame title.  */
 13522 
 13523 static int
 13524 store_mode_line_noprop (const char *string, int field_width, int precision)
 13525 {
 13526   const unsigned char *str = (const unsigned char *) string;
 13527   int n = 0;
 13528   ptrdiff_t dummy, nbytes;
 13529 
 13530   /* Copy at most PRECISION chars from STR.  */
 13531   nbytes = strlen (string);
 13532   n += c_string_width (str, nbytes, precision, &dummy, &nbytes);
 13533   while (nbytes--)
 13534     store_mode_line_noprop_char (*str++);
 13535 
 13536   /* Fill up with spaces until FIELD_WIDTH reached.  */
 13537   while (field_width > 0
 13538          && n < field_width)
 13539     {
 13540       store_mode_line_noprop_char (' ');
 13541       ++n;
 13542     }
 13543 
 13544   return n;
 13545 }
 13546 
 13547 /***********************************************************************
 13548                              Frame Titles
 13549  ***********************************************************************/
 13550 
 13551 #ifdef HAVE_WINDOW_SYSTEM
 13552 
 13553 /* Set the title of FRAME, if it has changed.  The title format is
 13554    Vicon_title_format if FRAME is iconified, otherwise it is
 13555    frame_title_format.  */
 13556 
 13557 void
 13558 gui_consider_frame_title (Lisp_Object frame)
 13559 {
 13560   struct frame *f = XFRAME (frame);
 13561   Lisp_Object format_data;
 13562 
 13563   if ((FRAME_WINDOW_P (f)
 13564        || FRAME_MINIBUF_ONLY_P (f)
 13565        || f->explicit_name)
 13566       && !FRAME_TOOLTIP_P (f))
 13567     {
 13568       /* Do we have more than one visible frame on this X display?  */
 13569       Lisp_Object tail, other_frame, fmt;
 13570       ptrdiff_t title_start;
 13571       char *title;
 13572       ptrdiff_t len;
 13573       struct it it;
 13574       specpdl_ref count = SPECPDL_INDEX ();
 13575 
 13576       FOR_EACH_FRAME (tail, other_frame)
 13577         {
 13578           struct frame *tf = XFRAME (other_frame);
 13579 
 13580           if (tf != f
 13581               && FRAME_KBOARD (tf) == FRAME_KBOARD (f)
 13582               && !FRAME_MINIBUF_ONLY_P (tf)
 13583               && !FRAME_PARENT_FRAME (tf)
 13584               && !FRAME_TOOLTIP_P (tf)
 13585               && (FRAME_VISIBLE_P (tf) || FRAME_ICONIFIED_P (tf)))
 13586             break;
 13587         }
 13588 
 13589       /* Set global variable indicating that multiple frames exist.  */
 13590       multiple_frames = CONSP (tail);
 13591 
 13592       /* select-frame calls resize_mini_window, which could resize the
 13593          mini-window and by that undo the effect of this redisplay
 13594          cycle wrt minibuffer and echo-area display.  Binding
 13595          inhibit-redisplay to t makes the call to resize_mini_window a
 13596          no-op, thus avoiding the adverse side effects.  */
 13597 
 13598       /* The following was moved before the record_unwind_protect form
 13599          below to inhibit redisplay also when restoring the selected
 13600          window/frame: This avoids that resize_mini_window sizes back
 13601          the minibuffer window of a temporarily selected frame.  See
 13602          Bug#34317.  */
 13603       specbind (Qinhibit_redisplay, Qt);
 13604 
 13605       /* Switch to the buffer of selected window of the frame.  Set up
 13606          mode_line_target so that display_mode_element will output
 13607          into mode_line_noprop_buf; then display the title.  Save the
 13608          original frame and selected window, and possibly the topmost
 13609          frame of the tty (for tty frames) into a vector; it will be
 13610          restored later.  */
 13611 
 13612       format_data = format_mode_line_unwind_data (f, current_buffer,
 13613                                                   selected_window,
 13614                                                   false);
 13615       record_unwind_protect (unwind_format_mode_line, format_data);
 13616 
 13617       Fselect_window (f->selected_window, Qt);
 13618       set_buffer_internal_1 (XBUFFER (XWINDOW (f->selected_window)->contents));
 13619       fmt = (FRAME_ICONIFIED_P (f) && !EQ (Vicon_title_format, Qt)
 13620              ? Vicon_title_format : Vframe_title_format);
 13621 
 13622       mode_line_target = MODE_LINE_TITLE;
 13623       title_start = MODE_LINE_NOPROP_LEN (0);
 13624       init_iterator (&it, XWINDOW (f->selected_window), -1, -1,
 13625                      NULL, DEFAULT_FACE_ID);
 13626       display_mode_element (&it, 0, -1, -1, fmt, Qnil, false);
 13627       len = MODE_LINE_NOPROP_LEN (title_start);
 13628       title = mode_line_noprop_buf + title_start;
 13629       /* Make sure that any raw bytes in the title are properly
 13630          represented by their multibyte sequences.  */
 13631       ptrdiff_t nchars = 0;
 13632       len = str_as_multibyte ((unsigned char *) title,
 13633                               mode_line_noprop_buf_end - title,
 13634                               len, &nchars);
 13635       unbind_to (count, Qnil);
 13636 
 13637       /* Set the title only if it's changed.  This avoids consing in
 13638          the common case where it hasn't.  (If it turns out that we've
 13639          already wasted too much time by walking through the list with
 13640          display_mode_element, then we might need to optimize at a
 13641          higher level than this.)  */
 13642       if ((! STRINGP (f->name)
 13643            || SBYTES (f->name) != len
 13644            || memcmp (title, SDATA (f->name), len) != 0)
 13645           && FRAME_TERMINAL (f)->implicit_set_name_hook)
 13646         {
 13647           Lisp_Object title_string = make_multibyte_string (title, nchars, len);
 13648           FRAME_TERMINAL (f)->implicit_set_name_hook (f, title_string, Qnil);
 13649         }
 13650     }
 13651 }
 13652 
 13653 #endif /* not HAVE_WINDOW_SYSTEM */
 13654 
 13655 
 13656 /***********************************************************************
 13657                               Menu Bars
 13658  ***********************************************************************/
 13659 
 13660 /* True if we will not redisplay all visible windows.  */
 13661 #define REDISPLAY_SOME_P()                              \
 13662   ((windows_or_buffers_changed == 0                     \
 13663     || windows_or_buffers_changed == REDISPLAY_SOME)    \
 13664    && (update_mode_lines == 0                           \
 13665        || update_mode_lines == REDISPLAY_SOME))
 13666 
 13667 static bool
 13668 needs_no_redisplay (struct window *w)
 13669 {
 13670   struct buffer *buffer = XBUFFER (w->contents);
 13671   struct frame *f = XFRAME (w->frame);
 13672   return (REDISPLAY_SOME_P ()
 13673           && !w->redisplay
 13674           && !w->update_mode_line
 13675           && !f->face_change
 13676           && !f->redisplay
 13677           && !buffer->text->redisplay
 13678           && window_point (w) == w->last_point);
 13679 }
 13680 
 13681 /* Prepare for redisplay by updating menu-bar item lists when
 13682    appropriate.  This can call eval.  */
 13683 
 13684 static void
 13685 prepare_menu_bars (void)
 13686 {
 13687   bool all_windows = windows_or_buffers_changed || update_mode_lines;
 13688   bool some_windows = REDISPLAY_SOME_P ();
 13689 
 13690   if (FUNCTIONP (Vpre_redisplay_function))
 13691     {
 13692       Lisp_Object windows = all_windows ? Qt : Qnil;
 13693       if (all_windows && some_windows)
 13694         {
 13695           Lisp_Object ws = window_list ();
 13696           for (windows = Qnil; CONSP (ws); ws = XCDR (ws))
 13697             {
 13698               Lisp_Object this = XCAR (ws);
 13699               struct window *w = XWINDOW (this);
 13700               /* Cf. conditions for redisplaying a window at the
 13701                  beginning of redisplay_window.  */
 13702               if (!needs_no_redisplay (w))
 13703                 windows = Fcons (this, windows);
 13704             }
 13705         }
 13706       safe__call1 (true, Vpre_redisplay_function, windows);
 13707     }
 13708 
 13709   /* Update all frame titles based on their buffer names, etc.  We do
 13710      this before the menu bars so that the buffer-menu will show the
 13711      up-to-date frame titles.  */
 13712 #ifdef HAVE_WINDOW_SYSTEM
 13713   if (all_windows)
 13714     {
 13715       Lisp_Object tail, frame;
 13716 
 13717       FOR_EACH_FRAME (tail, frame)
 13718         {
 13719           struct frame *f = XFRAME (frame);
 13720           struct window *w = XWINDOW (FRAME_SELECTED_WINDOW (f));
 13721           if (some_windows
 13722               && !f->redisplay
 13723               && !w->redisplay
 13724               && !XBUFFER (w->contents)->text->redisplay)
 13725             continue;
 13726 
 13727           if (!FRAME_TOOLTIP_P (f)
 13728               && (FRAME_ICONIFIED_P (f)
 13729                   || FRAME_VISIBLE_P (f) == 1
 13730                   /* Exclude TTY frames that are obscured because they
 13731                      are not the top frame on their console.  This is
 13732                      because gui_consider_frame_title actually switches
 13733                      to the frame, which for TTY frames means it is
 13734                      marked as garbaged, and will be completely
 13735                      redrawn on the next redisplay cycle.  This causes
 13736                      TTY frames to be completely redrawn, when there
 13737                      are more than one of them, even though nothing
 13738                      should be changed on display.  */
 13739                   || (FRAME_REDISPLAY_P (f) && FRAME_WINDOW_P (f))))
 13740             gui_consider_frame_title (frame);
 13741         }
 13742     }
 13743 #endif /* HAVE_WINDOW_SYSTEM */
 13744 
 13745   /* Update the menu bar item lists, if appropriate.  This has to be
 13746      done before any actual redisplay or generation of display lines.  */
 13747 
 13748   if (all_windows)
 13749     {
 13750       Lisp_Object tail, frame;
 13751       specpdl_ref count = SPECPDL_INDEX ();
 13752       /* True means that update_menu_bar has run its hooks
 13753          so any further calls to update_menu_bar shouldn't do so again.  */
 13754       bool menu_bar_hooks_run = false;
 13755 
 13756       record_unwind_save_match_data ();
 13757 
 13758       FOR_EACH_FRAME (tail, frame)
 13759         {
 13760           struct frame *f = XFRAME (frame);
 13761           struct window *w = XWINDOW (FRAME_SELECTED_WINDOW (f));
 13762 
 13763           /* Ignore tooltip frame.  */
 13764           if (FRAME_TOOLTIP_P (f))
 13765             continue;
 13766 
 13767           if (some_windows
 13768               && !f->redisplay
 13769               && !w->redisplay
 13770               && !XBUFFER (w->contents)->text->redisplay)
 13771             continue;
 13772 
 13773           if (!FRAME_PARENT_FRAME (f))
 13774             menu_bar_hooks_run = update_menu_bar (f, false, menu_bar_hooks_run);
 13775 
 13776           update_tab_bar (f, false);
 13777 #ifdef HAVE_WINDOW_SYSTEM
 13778           update_tool_bar (f, false);
 13779 #endif
 13780         }
 13781 
 13782       unbind_to (count, Qnil);
 13783     }
 13784   else
 13785     {
 13786       struct frame *sf = SELECTED_FRAME ();
 13787 
 13788       if (!FRAME_PARENT_FRAME (sf))
 13789         update_menu_bar (sf, true, false);
 13790 
 13791       update_tab_bar (sf, true);
 13792 #ifdef HAVE_WINDOW_SYSTEM
 13793       update_tool_bar (sf, true);
 13794 #endif
 13795     }
 13796 }
 13797 
 13798 
 13799 /* Update the menu bar item list for frame F.  This has to be done
 13800    before we start to fill in any display lines, because it can call
 13801    eval.
 13802 
 13803    If SAVE_MATCH_DATA, we must save and restore it here.
 13804 
 13805    If HOOKS_RUN, a previous call to update_menu_bar
 13806    already ran the menu bar hooks for this redisplay, so there
 13807    is no need to run them again.  The return value is the
 13808    updated value of this flag, to pass to the next call.  */
 13809 
 13810 static bool
 13811 update_menu_bar (struct frame *f, bool save_match_data, bool hooks_run)
 13812 {
 13813   Lisp_Object window;
 13814   struct window *w;
 13815 
 13816   /* If called recursively during a menu update, do nothing.  This can
 13817      happen when, for instance, an activate-menubar-hook causes a
 13818      redisplay.  */
 13819   if (inhibit_menubar_update)
 13820     return hooks_run;
 13821 
 13822   window = FRAME_SELECTED_WINDOW (f);
 13823   w = XWINDOW (window);
 13824 
 13825   if (FRAME_WINDOW_P (f)
 13826       ?
 13827 #ifdef HAVE_EXT_MENU_BAR
 13828       FRAME_EXTERNAL_MENU_BAR (f)
 13829 #else
 13830       FRAME_MENU_BAR_LINES (f) > 0
 13831 #endif
 13832       : FRAME_MENU_BAR_LINES (f) > 0)
 13833     {
 13834       /* If the user has switched buffers or windows, we need to
 13835          recompute to reflect the new bindings.  But we'll
 13836          recompute when update_mode_lines is set too; that means
 13837          that people can use force-mode-line-update to request
 13838          that the menu bar be recomputed.  The adverse effect on
 13839          the rest of the redisplay algorithm is about the same as
 13840          windows_or_buffers_changed anyway.  */
 13841       if (windows_or_buffers_changed
 13842           /* This used to test w->update_mode_line, but we believe
 13843              there is no need to recompute the menu in that case.  */
 13844           || update_mode_lines
 13845           || window_buffer_changed (w))
 13846         {
 13847           struct buffer *prev = current_buffer;
 13848           specpdl_ref count = SPECPDL_INDEX ();
 13849 
 13850           specbind (Qinhibit_menubar_update, Qt);
 13851 
 13852           set_buffer_internal_1 (XBUFFER (w->contents));
 13853           if (save_match_data)
 13854             record_unwind_save_match_data ();
 13855           if (NILP (Voverriding_local_map_menu_flag))
 13856             {
 13857               specbind (Qoverriding_terminal_local_map, Qnil);
 13858               specbind (Qoverriding_local_map, Qnil);
 13859             }
 13860 
 13861           if (!hooks_run)
 13862             {
 13863               /* Run the Lucid hook.  */
 13864               safe_run_hooks (Qactivate_menubar_hook);
 13865 
 13866               /* If it has changed current-menubar from previous value,
 13867                  really recompute the menu-bar from the value.  */
 13868               safe_run_hooks (Qmenu_bar_update_hook);
 13869 
 13870               hooks_run = true;
 13871             }
 13872 
 13873           XSETFRAME (Vmenu_updating_frame, f);
 13874           fset_menu_bar_items (f, menu_bar_items (FRAME_MENU_BAR_ITEMS (f)));
 13875 
 13876           /* Redisplay the menu bar in case we changed it.  */
 13877 #ifdef HAVE_EXT_MENU_BAR
 13878           if (FRAME_WINDOW_P (f))
 13879             {
 13880 #if defined (HAVE_NS)
 13881               /* All frames on Mac OS share the same menubar.  So only
 13882                  the selected frame should be allowed to set it.  */
 13883               if (f == SELECTED_FRAME ())
 13884 #endif
 13885                 set_frame_menubar (f, false);
 13886             }
 13887           else
 13888             /* On a terminal screen, the menu bar is an ordinary screen
 13889                line, and this makes it get updated.  */
 13890             w->update_mode_line = true;
 13891 #else /* ! (HAVE_EXT_MENU_BAR) */
 13892           /* In the non-toolkit version, the menu bar is an ordinary screen
 13893              line, and this makes it get updated.  */
 13894           w->update_mode_line = true;
 13895 #endif /* HAVE_EXT_MENU_BAR */
 13896 
 13897           unbind_to (count, Qnil);
 13898           set_buffer_internal_1 (prev);
 13899         }
 13900     }
 13901 
 13902   return hooks_run;
 13903 }
 13904 
 13905 
 13906 
 13907 /***********************************************************************
 13908                                Tab-bars
 13909  ***********************************************************************/
 13910 
 13911 /* Restore WINDOW as the selected window and its frame as the selected
 13912    frame.  If WINDOW is dead but the selected frame is live, make the
 13913    latter's selected window the selected window.  If both, WINDOW and
 13914    the selected frame, are dead, assign selected frame and window from
 13915    some arbitrary live frame.  Abort if no such frame can be found.  */
 13916 static void
 13917 restore_selected_window (Lisp_Object window)
 13918 {
 13919   if (WINDOW_LIVE_P (window))
 13920     /* If WINDOW is live, make it the selected window and its frame's
 13921        selected window and set the selected frame to its frame.  */
 13922     {
 13923       selected_window = window;
 13924       selected_frame = XWINDOW (window)->frame;
 13925       FRAME_SELECTED_WINDOW (XFRAME (selected_frame)) = window;
 13926     }
 13927   else if (FRAMEP (selected_frame) && FRAME_LIVE_P (XFRAME (selected_frame)))
 13928     /* If WINDOW is dead but the selected frame is still live, make the
 13929        latter's selected window the selected one.  */
 13930     selected_window = FRAME_SELECTED_WINDOW (XFRAME (selected_frame));
 13931   else
 13932     /* If WINDOW and the selected frame are dead, choose some live,
 13933        non-child and non-tooltip frame as the new selected frame and
 13934        make its selected window the selected window.  */
 13935     {
 13936       Lisp_Object tail;
 13937       Lisp_Object frame UNINIT;
 13938 
 13939       FOR_EACH_FRAME (tail, frame)
 13940         {
 13941           struct frame *f = XFRAME (frame);
 13942 
 13943           if (!FRAME_PARENT_FRAME (f) && !FRAME_TOOLTIP_P (f))
 13944             {
 13945               selected_frame = frame;
 13946               selected_window = FRAME_SELECTED_WINDOW (f);
 13947 
 13948               return;
 13949             }
 13950         }
 13951 
 13952       /* Abort if we cannot find a live frame.  */
 13953       emacs_abort ();
 13954     }
 13955 }
 13956 
 13957 /* Restore WINDOW, if live, as its frame's selected window.  */
 13958 static void
 13959 restore_frame_selected_window (Lisp_Object window)
 13960 {
 13961   if (WINDOW_LIVE_P (window))
 13962     /* If WINDOW is live, make it its frame's selected window.  If that
 13963        frame is the selected frame, make WINDOW the selected window as
 13964        well.  */
 13965     {
 13966       Lisp_Object frame = XWINDOW (window)->frame;
 13967 
 13968       FRAME_SELECTED_WINDOW (XFRAME (frame)) = window;
 13969       if (EQ (frame, selected_frame))
 13970         selected_window = window;
 13971     }
 13972 }
 13973 
 13974 /* Update the tab-bar item list for frame F.  This has to be done
 13975    before we start to fill in any display lines.  Called from
 13976    prepare_menu_bars.  If SAVE_MATCH_DATA, we must save
 13977    and restore it here.  */
 13978 
 13979 static void
 13980 update_tab_bar (struct frame *f, bool save_match_data)
 13981 {
 13982   bool do_update = false;
 13983 
 13984 #ifdef HAVE_WINDOW_SYSTEM
 13985   if (FRAME_WINDOW_P (f) && WINDOWP (f->tab_bar_window)) {
 13986     if (WINDOW_TOTAL_LINES (XWINDOW (f->tab_bar_window)) > 0)
 13987       do_update = true;
 13988   }
 13989   else
 13990 #endif
 13991   if (FRAME_TAB_BAR_LINES (f) > 0)
 13992     do_update = true;
 13993 
 13994   if (do_update)
 13995     {
 13996       Lisp_Object window;
 13997       struct window *w;
 13998 
 13999       window = FRAME_SELECTED_WINDOW (f);
 14000       w = XWINDOW (window);
 14001 
 14002       /* If the user has switched buffers or windows, we need to
 14003          recompute to reflect the new bindings.  But we'll
 14004          recompute when update_mode_lines is set too; that means
 14005          that people can use force-mode-line-update to request
 14006          that the menu bar be recomputed.  The adverse effect on
 14007          the rest of the redisplay algorithm is about the same as
 14008          windows_or_buffers_changed anyway.  */
 14009       if (windows_or_buffers_changed
 14010           || w->update_mode_line
 14011           || update_mode_lines
 14012           || window_buffer_changed (w))
 14013         {
 14014           struct buffer *prev = current_buffer;
 14015           specpdl_ref count = SPECPDL_INDEX ();
 14016           Lisp_Object new_tab_bar;
 14017           int new_n_tab_bar;
 14018 
 14019           /* Set current_buffer to the buffer of the selected
 14020              window of the frame, so that we get the right local
 14021              keymaps.  */
 14022           set_buffer_internal_1 (XBUFFER (w->contents));
 14023 
 14024           /* Save match data, if we must.  */
 14025           if (save_match_data)
 14026             record_unwind_save_match_data ();
 14027 
 14028           /* Make sure that we don't accidentally use bogus keymaps.  */
 14029           if (NILP (Voverriding_local_map_menu_flag))
 14030             {
 14031               specbind (Qoverriding_terminal_local_map, Qnil);
 14032               specbind (Qoverriding_local_map, Qnil);
 14033             }
 14034 
 14035           /* We must temporarily set the selected frame to this frame
 14036              before calling tab_bar_items, because the calculation of
 14037              the tab-bar keymap uses the selected frame (see
 14038              `tab-bar-make-keymap' in tab-bar.el).  */
 14039           eassert (EQ (selected_window,
 14040                        /* Since we only explicitly preserve selected_frame,
 14041                           check that selected_window would be redundant.  */
 14042                        XFRAME (selected_frame)->selected_window));
 14043 #ifdef HAVE_WINDOW_SYSTEM
 14044           Lisp_Object frame;
 14045           record_unwind_protect (restore_selected_window, selected_window);
 14046           XSETFRAME (frame, f);
 14047           selected_frame = frame;
 14048           selected_window = FRAME_SELECTED_WINDOW (f);
 14049 #endif
 14050 
 14051           /* Build desired tab-bar items from keymaps.  */
 14052           new_tab_bar
 14053             = tab_bar_items (Fcopy_sequence (f->tab_bar_items),
 14054                               &new_n_tab_bar);
 14055 
 14056           /* Redisplay the tab-bar if we changed it.  */
 14057           if (new_n_tab_bar != f->n_tab_bar_items
 14058               || NILP (Fequal (new_tab_bar, f->tab_bar_items)))
 14059             {
 14060               /* Redisplay that happens asynchronously due to an expose event
 14061                  may access f->tab_bar_items.  Make sure we update both
 14062                  variables within BLOCK_INPUT so no such event interrupts.  */
 14063               block_input ();
 14064               fset_tab_bar_items (f, new_tab_bar);
 14065               f->n_tab_bar_items = new_n_tab_bar;
 14066               w->update_mode_line = true;
 14067               unblock_input ();
 14068             }
 14069 
 14070           unbind_to (count, Qnil);
 14071           set_buffer_internal_1 (prev);
 14072         }
 14073     }
 14074 }
 14075 
 14076 /* Redisplay the tab bar in the frame for window W.
 14077 
 14078    The tab bar of X frames that don't have X toolkit support is
 14079    displayed in a special window W->frame->tab_bar_window.
 14080 
 14081    The tab bar of terminal frames is treated specially as far as
 14082    glyph matrices are concerned.  Tab bar lines are not part of
 14083    windows, so the update is done directly on the frame matrix rows
 14084    for the tab bar.  */
 14085 
 14086 static void
 14087 display_tab_bar (struct window *w)
 14088 {
 14089   struct frame *f = XFRAME (WINDOW_FRAME (w));
 14090   struct it it;
 14091   Lisp_Object items;
 14092   int i;
 14093 
 14094   /* Don't do all this for graphical frames.  */
 14095 #ifdef HAVE_NTGUI
 14096   if (FRAME_W32_P (f))
 14097     return;
 14098 #endif
 14099 #if defined (USE_X_TOOLKIT) || defined (USE_GTK)
 14100   if (FRAME_X_P (f))
 14101     return;
 14102 #endif
 14103 
 14104 #ifdef HAVE_NS
 14105   if (FRAME_NS_P (f))
 14106     return;
 14107 #endif /* HAVE_NS */
 14108 
 14109 #if defined (USE_X_TOOLKIT) || defined (USE_GTK)
 14110   eassert (!FRAME_WINDOW_P (f));
 14111   init_iterator (&it, w, -1, -1, f->desired_matrix->rows
 14112                  + (FRAME_MENU_BAR_LINES (f) > 0 ? 1 : 0),
 14113                  TAB_BAR_FACE_ID);
 14114   it.first_visible_x = 0;
 14115   it.last_visible_x = FRAME_PIXEL_WIDTH (f);
 14116 #elif defined (HAVE_X_WINDOWS) /* X without toolkit.  */
 14117   if (FRAME_WINDOW_P (f))
 14118     {
 14119       /* Tab bar lines are displayed in the desired matrix of the
 14120          dummy window tab_bar_window.  */
 14121       struct window *tab_w;
 14122       tab_w = XWINDOW (f->tab_bar_window);
 14123       init_iterator (&it, tab_w, -1, -1, tab_w->desired_matrix->rows,
 14124                      TAB_BAR_FACE_ID);
 14125       it.first_visible_x = 0;
 14126       it.last_visible_x = FRAME_PIXEL_WIDTH (f);
 14127     }
 14128   else
 14129 #endif /* not USE_X_TOOLKIT and not USE_GTK */
 14130     {
 14131       /* This is a TTY frame, i.e. character hpos/vpos are used as
 14132          pixel x/y.  */
 14133       init_iterator (&it, w, -1, -1, f->desired_matrix->rows
 14134                      + (FRAME_MENU_BAR_LINES (f) > 0 ? 1 : 0),
 14135                      TAB_BAR_FACE_ID);
 14136       it.first_visible_x = 0;
 14137       it.last_visible_x = FRAME_COLS (f);
 14138     }
 14139 
 14140   /* FIXME: This should be controlled by a user option.  See the
 14141      comments in redisplay_tool_bar and display_mode_line about
 14142      this.  */
 14143   it.paragraph_embedding = L2R;
 14144 
 14145   /* Clear all rows of the tab bar.  */
 14146   for (i = 0; i < FRAME_TAB_BAR_LINES (f); ++i)
 14147     {
 14148       struct glyph_row *row = it.glyph_row + i;
 14149       clear_glyph_row (row);
 14150       row->enabled_p = true;
 14151       row->full_width_p = true;
 14152       row->reversed_p = false;
 14153     }
 14154 
 14155   /* Display all items of the tab bar.  */
 14156   items = it.f->tab_bar_items;
 14157   int j;
 14158   for (i = 0, j = 0; i < it.f->n_tab_bar_items; ++i, j += TAB_BAR_ITEM_NSLOTS)
 14159     {
 14160       Lisp_Object string = AREF (items, j + TAB_BAR_ITEM_CAPTION);
 14161 
 14162       /* Stop at nil string.  */
 14163       if (NILP (string))
 14164         break;
 14165 
 14166       if (it.current_x < it.last_visible_x)
 14167         display_string (NULL, string, Qnil, 0, 0, &it,
 14168                         SCHARS (string), 0, 0, STRING_MULTIBYTE (string));
 14169     }
 14170 
 14171   /* Fill out the line with spaces.  */
 14172   if (it.current_x < it.last_visible_x)
 14173     display_string ("", Qnil, Qnil, 0, 0, &it, -1, 0, 0, -1);
 14174 
 14175   /* Compute the total height of the lines.  */
 14176   compute_line_metrics (&it);
 14177 }
 14178 
 14179 #ifdef HAVE_WINDOW_SYSTEM
 14180 
 14181 /* Set F->desired_tab_bar_string to a Lisp string representing frame
 14182    F's desired tab-bar contents.  F->tab_bar_items must have
 14183    been set up previously by calling prepare_menu_bars.  */
 14184 
 14185 static void
 14186 build_desired_tab_bar_string (struct frame *f)
 14187 {
 14188   int i;
 14189   Lisp_Object caption;
 14190 
 14191   caption = Qnil;
 14192 
 14193   /* Prepare F->desired_tab_bar_string.  Make a new string.  */
 14194   fset_desired_tab_bar_string (f, build_string (""));
 14195 
 14196   /* Put a `display' property on the string for the captions to display,
 14197      put a `menu_item' property on tab-bar items with a value that
 14198      is the index of the item in F's tab-bar item vector.  */
 14199   for (i = 0; i < f->n_tab_bar_items; ++i)
 14200     {
 14201 #define PROP(IDX) \
 14202   AREF (f->tab_bar_items, i * TAB_BAR_ITEM_NSLOTS + (IDX))
 14203 
 14204       caption = Fcopy_sequence (PROP (TAB_BAR_ITEM_CAPTION));
 14205 
 14206       /* Put a `display' text property on the string for the caption to
 14207          display.  Put a `menu-item' property on the string that gives
 14208          the start of this item's properties in the tab-bar items
 14209          vector.  */
 14210       AUTO_LIST2 (props, Qmenu_item, make_fixnum (i * TAB_BAR_ITEM_NSLOTS));
 14211 
 14212       Fadd_text_properties (make_fixnum (0), make_fixnum (SCHARS (caption)),
 14213                             props, caption);
 14214 
 14215       f->desired_tab_bar_string =
 14216         concat2 (f->desired_tab_bar_string, caption);
 14217 
 14218 #undef PROP
 14219     }
 14220 }
 14221 
 14222 
 14223 /* Display one line of the tab-bar of frame IT->f.
 14224 
 14225    HEIGHT specifies the desired height of the tab-bar line.
 14226    If the actual height of the glyph row is less than HEIGHT, the
 14227    row's height is increased to HEIGHT, and the icons are centered
 14228    vertically in the new height.
 14229 
 14230    If HEIGHT is -1, we are counting needed tab-bar lines, so don't
 14231    count a final empty row in case the tab-bar width exactly matches
 14232    the window width.
 14233 */
 14234 
 14235 static void
 14236 display_tab_bar_line (struct it *it, int height)
 14237 {
 14238   struct glyph_row *row = it->glyph_row;
 14239   int max_x = it->last_visible_x;
 14240   struct glyph *last;
 14241 
 14242   /* Don't extend on a previously drawn tab bar items (Bug#16058).  */
 14243   clear_glyph_row (row);
 14244   row->enabled_p = true;
 14245   row->y = it->current_y;
 14246 
 14247   /* Note that this isn't made use of if the face hasn't a box,
 14248      so there's no need to check the face here.  */
 14249   it->start_of_box_run_p = true;
 14250 
 14251   bool enough = false;
 14252   while (it->current_x < max_x)
 14253     {
 14254       int x, n_glyphs_before, i, nglyphs;
 14255       struct it it_before;
 14256 
 14257       /* Get the next display element.  */
 14258       if (!get_next_display_element (it))
 14259         {
 14260           /* Don't count empty row if we are counting needed tab-bar lines.  */
 14261           if (height < 0 && !it->hpos)
 14262             return;
 14263           break;
 14264         }
 14265 
 14266       /* Produce glyphs.  */
 14267       n_glyphs_before = row->used[TEXT_AREA];
 14268       it_before = *it;
 14269 
 14270       PRODUCE_GLYPHS (it);
 14271 
 14272       nglyphs = row->used[TEXT_AREA] - n_glyphs_before;
 14273       i = 0;
 14274       x = it_before.current_x;
 14275       while (i < nglyphs)
 14276         {
 14277           struct glyph *glyph = row->glyphs[TEXT_AREA] + n_glyphs_before + i;
 14278 
 14279           if (x + glyph->pixel_width > max_x)
 14280             {
 14281               /* Glyph doesn't fit on line.  Backtrack.  */
 14282               row->used[TEXT_AREA] = n_glyphs_before;
 14283               *it = it_before;
 14284               /* If this is the only glyph on this line, it will never fit on the
 14285                  tab-bar, so skip it.  But ensure there is at least one glyph,
 14286                  so we don't accidentally disable the tab-bar.  */
 14287               if (n_glyphs_before == 0
 14288                   && (it->vpos > 0 || IT_STRING_CHARPOS (*it) < it->end_charpos-1))
 14289                 break;
 14290               goto out;
 14291             }
 14292 
 14293           ++it->hpos;
 14294           x += glyph->pixel_width;
 14295           ++i;
 14296         }
 14297 
 14298       enough = ITERATOR_AT_END_OF_LINE_P (it);
 14299       set_iterator_to_next (it, true);
 14300 
 14301       /* Stop at line end.  */
 14302       if (enough)
 14303         break;
 14304     }
 14305 
 14306  out:;
 14307 
 14308   row->displays_text_p = row->used[TEXT_AREA] != 0;
 14309 
 14310   /* Use default face for the border below the tab bar.
 14311 
 14312      FIXME: When auto-resize-tab-bars is grow-only, there is
 14313      no additional border below the possibly empty tab-bar lines.
 14314      So to make the extra empty lines look "normal", we have to
 14315      use the tab-bar face for the border too.  */
 14316   if (!MATRIX_ROW_DISPLAYS_TEXT_P (row)
 14317       && !EQ (Vauto_resize_tab_bars, Qgrow_only))
 14318     it->face_id = DEFAULT_FACE_ID;
 14319 
 14320   extend_face_to_end_of_line (it);
 14321   last = row->glyphs[TEXT_AREA] + row->used[TEXT_AREA] - 1;
 14322   last->right_box_line_p = true;
 14323   if (last == row->glyphs[TEXT_AREA])
 14324     last->left_box_line_p = true;
 14325 
 14326   /* Make line the desired height and center it vertically.  */
 14327   if ((height -= it->max_ascent + it->max_descent) > 0)
 14328     {
 14329       /* Don't add more than one line height.  */
 14330       height %= FRAME_LINE_HEIGHT (it->f);
 14331       it->max_ascent += height / 2;
 14332       it->max_descent += (height + 1) / 2;
 14333     }
 14334 
 14335   compute_line_metrics (it);
 14336 
 14337   /* If line is empty, make it occupy the rest of the tab-bar.  */
 14338   if (!MATRIX_ROW_DISPLAYS_TEXT_P (row))
 14339     {
 14340       row->height = row->phys_height = it->last_visible_y - row->y;
 14341       row->visible_height = row->height;
 14342       row->ascent = row->phys_ascent = 0;
 14343       row->extra_line_spacing = 0;
 14344     }
 14345 
 14346   row->full_width_p = true;
 14347   row->continued_p = false;
 14348   row->truncated_on_left_p = false;
 14349   row->truncated_on_right_p = false;
 14350 
 14351   it->current_x = it->hpos = 0;
 14352   it->current_y += row->height;
 14353   ++it->vpos;
 14354   ++it->glyph_row;
 14355 }
 14356 
 14357 
 14358 /* Value is the number of pixels needed to make all tab-bar items of
 14359    frame F visible.  The actual number of glyph rows needed is
 14360    returned in *N_ROWS if non-NULL.  */
 14361 static int
 14362 tab_bar_height (struct frame *f, int *n_rows, bool pixelwise)
 14363 {
 14364   struct window *w = XWINDOW (f->tab_bar_window);
 14365   struct it it;
 14366   /* tab_bar_height is called from redisplay_tab_bar after building
 14367      the desired matrix, so use (unused) mode-line row as temporary row to
 14368      avoid destroying the first tab-bar row.  */
 14369   struct glyph_row *temp_row = MATRIX_MODE_LINE_ROW (w->desired_matrix);
 14370 
 14371   /* Initialize an iterator for iteration over
 14372      F->desired_tab_bar_string in the tab-bar window of frame F.  */
 14373   init_iterator (&it, w, -1, -1, temp_row, TAB_BAR_FACE_ID);
 14374   temp_row->reversed_p = false;
 14375   it.first_visible_x = 0;
 14376   it.last_visible_x = WINDOW_PIXEL_WIDTH (w);
 14377   reseat_to_string (&it, NULL, f->desired_tab_bar_string,
 14378                     0, 0, 0, STRING_MULTIBYTE (f->desired_tab_bar_string));
 14379   it.paragraph_embedding = L2R;
 14380 
 14381   clear_glyph_row (temp_row);
 14382   while (!ITERATOR_AT_END_P (&it))
 14383     {
 14384       it.glyph_row = temp_row;
 14385       display_tab_bar_line (&it, -1);
 14386     }
 14387   clear_glyph_row (temp_row);
 14388 
 14389   /* f->n_tab_bar_rows == 0 means "unknown"; -1 means no tab-bar.  */
 14390   if (n_rows)
 14391     *n_rows = it.vpos > 0 ? it.vpos : -1;
 14392 
 14393   if (pixelwise)
 14394     return it.current_y;
 14395   else
 14396     return (it.current_y + FRAME_LINE_HEIGHT (f) - 1) / FRAME_LINE_HEIGHT (f);
 14397 }
 14398 
 14399 DEFUN ("tab-bar-height", Ftab_bar_height, Stab_bar_height,
 14400        0, 2, 0,
 14401        doc: /* Return the number of lines occupied by the tab bar of FRAME.
 14402 If FRAME is nil or omitted, use the selected frame.  Optional argument
 14403 PIXELWISE non-nil means return the height of the tab bar in pixels.  */)
 14404   (Lisp_Object frame, Lisp_Object pixelwise)
 14405 {
 14406   int height = 0;
 14407 
 14408   struct frame *f = decode_any_frame (frame);
 14409 
 14410   if (WINDOWP (f->tab_bar_window)
 14411       && WINDOW_PIXEL_HEIGHT (XWINDOW (f->tab_bar_window)) > 0)
 14412     {
 14413       update_tab_bar (f, true);
 14414       if (f->n_tab_bar_items)
 14415         {
 14416           build_desired_tab_bar_string (f);
 14417           height = tab_bar_height (f, NULL, !NILP (pixelwise));
 14418         }
 14419     }
 14420 
 14421   return make_fixnum (height);
 14422 }
 14423 
 14424 
 14425 /* Display the tab-bar of frame F.  Value is true if tab-bar's
 14426    height should be changed.  */
 14427 static bool
 14428 redisplay_tab_bar (struct frame *f)
 14429 {
 14430   struct window *w;
 14431   struct it it;
 14432   struct glyph_row *row;
 14433 
 14434   f->tab_bar_redisplayed = true;
 14435 
 14436   /* If frame hasn't a tab-bar window or if it is zero-height, don't
 14437      do anything.  This means you must start with tab-bar-lines
 14438      non-zero to get the auto-sizing effect.  Or in other words, you
 14439      can turn off tab-bars by specifying tab-bar-lines zero.  */
 14440   if (!WINDOWP (f->tab_bar_window)
 14441       || (w = XWINDOW (f->tab_bar_window),
 14442           WINDOW_TOTAL_LINES (w) == 0))
 14443     {
 14444       /* Even if we do not display a tab bar initially, still pretend
 14445          that we have resized it.  This avoids that a later activation
 14446          of the tab bar resizes the frame, despite of the fact that the
 14447          setting of 'frame-inhibit-implied-resize' should inhibit it
 14448          (Bug#52986).  */
 14449       f->tab_bar_resized = true;
 14450 
 14451       return false;
 14452     }
 14453 
 14454   /* Build a string that represents the contents of the tab-bar.  */
 14455   build_desired_tab_bar_string (f);
 14456 
 14457   int new_nrows;
 14458   int new_height = tab_bar_height (f, &new_nrows, true);
 14459 
 14460   if (f->n_tab_bar_rows == 0)
 14461     {
 14462       f->n_tab_bar_rows = new_nrows;
 14463       if (new_height != WINDOW_PIXEL_HEIGHT (w))
 14464         frame_default_tab_bar_height = new_height;
 14465     }
 14466 
 14467   /* If new_height or new_nrows indicate that we need to enlarge or
 14468      shrink the tab-bar window, we can return right away.  */
 14469   if (new_nrows > f->n_tab_bar_rows
 14470       || (EQ (Vauto_resize_tab_bars, Qgrow_only)
 14471           && !f->minimize_tab_bar_window_p
 14472           && new_height > WINDOW_PIXEL_HEIGHT (w))
 14473       || (! EQ (Vauto_resize_tab_bars, Qgrow_only)
 14474           && new_height < WINDOW_PIXEL_HEIGHT (w)))
 14475     {
 14476       if (FRAME_TERMINAL (f)->change_tab_bar_height_hook)
 14477         FRAME_TERMINAL (f)->change_tab_bar_height_hook (f, new_height);
 14478       if (new_nrows != f->n_tab_bar_rows)
 14479         f->n_tab_bar_rows = new_nrows;
 14480       clear_glyph_matrix (w->desired_matrix);
 14481       f->fonts_changed = true;
 14482       return true;
 14483     }
 14484 
 14485   /* Set up an iterator for the tab-bar window.  */
 14486   init_iterator (&it, w, -1, -1, w->desired_matrix->rows, TAB_BAR_FACE_ID);
 14487   it.first_visible_x = 0;
 14488   it.last_visible_x = WINDOW_PIXEL_WIDTH (w);
 14489   row = it.glyph_row;
 14490   row->reversed_p = false;
 14491   reseat_to_string (&it, NULL, f->desired_tab_bar_string, 0, 0, 0,
 14492                     STRING_MULTIBYTE (f->desired_tab_bar_string));
 14493   /* FIXME: This should be controlled by a user option.  But it
 14494      doesn't make sense to have an R2L tab bar if the menu bar cannot
 14495      be drawn also R2L, and making the menu bar R2L is tricky due
 14496      tabkit-specific code that implements it.  If an R2L tab bar is
 14497      ever supported, display_tab_bar_line should also be augmented to
 14498      call unproduce_glyphs like display_line and display_string
 14499      do.  */
 14500   it.paragraph_embedding = L2R;
 14501 
 14502   /* Display as many lines as needed to display all tab-bar items.  */
 14503 
 14504   if (f->n_tab_bar_rows > 0)
 14505     {
 14506       int border, rows, height, extra;
 14507 
 14508       if (TYPE_RANGED_FIXNUMP (int, Vtab_bar_border))
 14509         border = XFIXNUM (Vtab_bar_border);
 14510       else if (EQ (Vtab_bar_border, Qinternal_border_width))
 14511         border = FRAME_INTERNAL_BORDER_WIDTH (f);
 14512       else if (EQ (Vtab_bar_border, Qborder_width))
 14513         border = f->border_width;
 14514       else
 14515         border = 0;
 14516       if (border < 0)
 14517         border = 0;
 14518 
 14519       rows = f->n_tab_bar_rows;
 14520       height = max (1, (it.last_visible_y - border) / rows);
 14521       extra = it.last_visible_y - border - height * rows;
 14522 
 14523       while (it.current_y < it.last_visible_y)
 14524         {
 14525           int h = 0;
 14526           if (extra > 0 && rows-- > 0)
 14527             {
 14528               h = (extra + rows - 1) / rows;
 14529               extra -= h;
 14530             }
 14531           display_tab_bar_line (&it, height + h);
 14532         }
 14533     }
 14534   else
 14535     {
 14536       while (it.current_y < it.last_visible_y)
 14537         display_tab_bar_line (&it, 0);
 14538     }
 14539 
 14540   /* It doesn't make much sense to try scrolling in the tab-bar
 14541      window, so don't do it.  */
 14542   w->desired_matrix->no_scrolling_p = true;
 14543   w->must_be_updated_p = true;
 14544 
 14545   if (!NILP (Vauto_resize_tab_bars))
 14546     {
 14547       bool change_height_p = false;
 14548 
 14549       /* If we couldn't display everything, change the tab-bar's
 14550          height if there is room for more.  */
 14551       if (IT_STRING_CHARPOS (it) < it.end_charpos)
 14552         change_height_p = true;
 14553 
 14554       /* We subtract 1 because display_tab_bar_line advances the
 14555          glyph_row pointer before returning to its caller.  We want to
 14556          examine the last glyph row produced by
 14557          display_tab_bar_line.  */
 14558       row = it.glyph_row - 1;
 14559 
 14560       /* If there are blank lines at the end, except for a partially
 14561          visible blank line at the end that is smaller than
 14562          FRAME_LINE_HEIGHT, change the tab-bar's height.  */
 14563       if (!MATRIX_ROW_DISPLAYS_TEXT_P (row)
 14564           && row->height >= FRAME_LINE_HEIGHT (f))
 14565         change_height_p = true;
 14566 
 14567       /* If row displays tab-bar items, but is partially visible,
 14568          change the tab-bar's height.  */
 14569       if (MATRIX_ROW_DISPLAYS_TEXT_P (row)
 14570           && MATRIX_ROW_BOTTOM_Y (row) > it.last_visible_y)
 14571         change_height_p = true;
 14572 
 14573       /* Resize windows as needed by changing the `tab-bar-lines'
 14574          frame parameter.  */
 14575       if (change_height_p)
 14576         {
 14577           int nrows;
 14578           int new_height = tab_bar_height (f, &nrows, true);
 14579 
 14580           change_height_p = ((EQ (Vauto_resize_tab_bars, Qgrow_only)
 14581                               && !f->minimize_tab_bar_window_p)
 14582                              ? (new_height > WINDOW_PIXEL_HEIGHT (w))
 14583                              : (new_height != WINDOW_PIXEL_HEIGHT (w)));
 14584           f->minimize_tab_bar_window_p = false;
 14585 
 14586           if (change_height_p)
 14587             {
 14588               if (FRAME_TERMINAL (f)->change_tab_bar_height_hook)
 14589                 FRAME_TERMINAL (f)->change_tab_bar_height_hook (f, new_height);
 14590               frame_default_tab_bar_height = new_height;
 14591               clear_glyph_matrix (w->desired_matrix);
 14592               f->n_tab_bar_rows = nrows;
 14593               f->fonts_changed = true;
 14594 
 14595               return true;
 14596             }
 14597         }
 14598     }
 14599 
 14600   f->minimize_tab_bar_window_p = false;
 14601   return false;
 14602 }
 14603 
 14604 /* Get information about the tab-bar item which is displayed in GLYPH
 14605    on frame F.  Return in *PROP_IDX the index where tab-bar item
 14606    properties start in F->tab_bar_items.  Return in CLOSE_P an
 14607    indication whether the click was on the close-tab icon of the tab.
 14608    Value is false if GLYPH doesn't display a tab-bar item.  */
 14609 
 14610 static bool
 14611 tab_bar_item_info (struct frame *f, struct glyph *glyph,
 14612                    int *prop_idx, bool *close_p)
 14613 {
 14614   Lisp_Object prop;
 14615   ptrdiff_t charpos;
 14616 
 14617   /* This function can be called asynchronously, which means we must
 14618      exclude any possibility that Fget_text_property signals an
 14619      error.  */
 14620   charpos = min (SCHARS (f->current_tab_bar_string), glyph->charpos);
 14621   charpos = max (0, charpos);
 14622 
 14623   /* Get the text property `menu-item' at pos. The value of that
 14624      property is the start index of this item's properties in
 14625      F->tab_bar_items.  */
 14626   prop = Fget_text_property (make_fixnum (charpos),
 14627                              Qmenu_item, f->current_tab_bar_string);
 14628   if (! FIXNUMP (prop))
 14629     return false;
 14630 
 14631   *prop_idx = XFIXNUM (prop);
 14632 
 14633   if (close_p)
 14634     *close_p = !NILP (Fget_text_property (make_fixnum (charpos),
 14635                                           Qclose_tab,
 14636                                           f->current_tab_bar_string));
 14637 
 14638   return true;
 14639 }
 14640 
 14641 
 14642 /* Get information about the tab-bar item at position X/Y on frame F's
 14643    tab bar window.
 14644 
 14645    Set *GLYPH to a pointer to the glyph of the tab-bar item in the
 14646    current matrix of the tab-bar window of F, or NULL if not on a
 14647    tab-bar item.  Return in *PROP_IDX the index of the tab-bar item in
 14648    F->tab_bar_items.
 14649 
 14650    Place the window-relative vpos of Y in *VPOS, and the
 14651    window-relative hpos of X in *HPOS.  If CLOSE_P, set it to whether
 14652    or not the tab bar item represents a button that should close a
 14653    tab.
 14654 
 14655    Value is
 14656 
 14657    -1   if X/Y is not on a tab-bar item
 14658    0    if X/Y is on the same item that was highlighted before.
 14659    1    otherwise.  */
 14660 
 14661 static int
 14662 get_tab_bar_item (struct frame *f, int x, int y, struct glyph **glyph,
 14663                   int *hpos, int *vpos, int *prop_idx, bool *close_p)
 14664 {
 14665   struct window *w = XWINDOW (f->tab_bar_window);
 14666   int area;
 14667 
 14668   /* Find the glyph under X/Y.  */
 14669   *glyph = x_y_to_hpos_vpos (w, x, y, hpos, vpos, 0, 0, &area);
 14670   if (*glyph == NULL)
 14671     return -1;
 14672 
 14673   /* Get the start of this tab-bar item's properties in
 14674      f->tab_bar_items.  */
 14675   if (!tab_bar_item_info (f, *glyph, prop_idx, close_p))
 14676     return -1;
 14677 
 14678   return *prop_idx == f->last_tab_bar_item ? 0 : 1;
 14679 }
 14680 
 14681 /* EXPORT:
 14682 
 14683    Like `get_tab_bar_item'.  However, don't return anything for GLYPH,
 14684    HPOS, or VPOS, and treat X and Y as relative to F itself, as
 14685    opposed to its tab bar window.  */
 14686 
 14687 int
 14688 get_tab_bar_item_kbd (struct frame *f, int x, int y, int *prop_idx,
 14689                       bool *close_p)
 14690 {
 14691   struct window *w;
 14692   int area, vpos, hpos;
 14693   struct glyph *glyph;
 14694 
 14695   w = XWINDOW (f->tab_bar_window);
 14696 
 14697   /* Convert X and Y to window coordinates.  */
 14698   frame_to_window_pixel_xy (w, &x, &y);
 14699 
 14700   /* Find the glyph under X/Y.  */
 14701   glyph = x_y_to_hpos_vpos (w, x, y, &hpos, &vpos, 0,
 14702                             0, &area);
 14703   if (glyph == NULL)
 14704     return -1;
 14705 
 14706   /* Get the start of this tab-bar item's properties in
 14707      f->tab_bar_items.  */
 14708   if (!tab_bar_item_info (f, glyph, prop_idx, close_p))
 14709     return -1;
 14710 
 14711   return *prop_idx == f->last_tab_bar_item ? 0 : 1;
 14712 }
 14713 
 14714 /* EXPORT:
 14715    Handle mouse button event on the tab-bar of frame F, at
 14716    frame-relative coordinates X/Y.  DOWN_P is true for a button press,
 14717    false for button release.  MODIFIERS is event modifiers for button
 14718    release.  */
 14719 
 14720 Lisp_Object
 14721 handle_tab_bar_click (struct frame *f, int x, int y, bool down_p,
 14722                       int modifiers)
 14723 {
 14724   Mouse_HLInfo *hlinfo = MOUSE_HL_INFO (f);
 14725   struct window *w = XWINDOW (f->tab_bar_window);
 14726   int hpos, vpos, prop_idx;
 14727   bool close_p;
 14728   struct glyph *glyph;
 14729   Lisp_Object enabled_p;
 14730   int ts;
 14731 
 14732   frame_to_window_pixel_xy (w, &x, &y);
 14733   ts = get_tab_bar_item (f, x, y, &glyph, &hpos, &vpos, &prop_idx, &close_p);
 14734   if (ts == -1)
 14735     return Fcons (Qtab_bar, Qnil);
 14736 
 14737   /* If item is disabled, do nothing.  */
 14738   enabled_p = AREF (f->tab_bar_items, prop_idx + TAB_BAR_ITEM_ENABLED_P);
 14739   if (NILP (enabled_p))
 14740     return Qnil;
 14741 
 14742   if (down_p)
 14743     {
 14744       /* Show the clicked button in pressed state.  */
 14745       if (!NILP (Vmouse_highlight))
 14746         show_mouse_face (hlinfo, DRAW_IMAGE_SUNKEN);
 14747       f->last_tab_bar_item = prop_idx; /* record the pressed tab */
 14748     }
 14749   else
 14750     {
 14751       /* Show item in released state.  */
 14752       if (!NILP (Vmouse_highlight))
 14753         show_mouse_face (hlinfo, DRAW_IMAGE_RAISED);
 14754       f->last_tab_bar_item = -1;
 14755     }
 14756 
 14757   Lisp_Object caption =
 14758     Fcopy_sequence (AREF (f->tab_bar_items, prop_idx + TAB_BAR_ITEM_CAPTION));
 14759 
 14760   AUTO_LIST2 (props, Qmenu_item,
 14761               list3 (AREF (f->tab_bar_items, prop_idx + TAB_BAR_ITEM_KEY),
 14762                      AREF (f->tab_bar_items, prop_idx + TAB_BAR_ITEM_BINDING),
 14763                      close_p ? Qt : Qnil));
 14764 
 14765   Fadd_text_properties (make_fixnum (0), make_fixnum (SCHARS (caption)),
 14766                         props, caption);
 14767 
 14768   return Fcons (Qtab_bar, Fcons (caption, make_fixnum (0)));
 14769 }
 14770 
 14771 
 14772 /* Possibly highlight a tab-bar item on frame F when mouse moves to
 14773    tab-bar window-relative coordinates X/Y.  Called from
 14774    note_mouse_highlight.  */
 14775 
 14776 static void
 14777 note_tab_bar_highlight (struct frame *f, int x, int y)
 14778 {
 14779   Lisp_Object window = f->tab_bar_window;
 14780   struct window *w = XWINDOW (window);
 14781   Mouse_HLInfo *hlinfo = MOUSE_HL_INFO (f);
 14782   int hpos, vpos;
 14783   struct glyph *glyph;
 14784   struct glyph_row *row;
 14785   int i;
 14786   Lisp_Object enabled_p;
 14787   int prop_idx;
 14788   bool close_p;
 14789   enum draw_glyphs_face draw = DRAW_IMAGE_RAISED;
 14790   int rc;
 14791 
 14792   /* Function note_mouse_highlight is called with negative X/Y
 14793      values when mouse moves outside of the frame.  */
 14794   if (x <= 0 || y <= 0)
 14795     {
 14796       clear_mouse_face (hlinfo);
 14797       return;
 14798     }
 14799 
 14800   rc = get_tab_bar_item (f, x, y, &glyph, &hpos, &vpos, &prop_idx, &close_p);
 14801   if (rc < 0)
 14802     {
 14803       /* Not on tab-bar item.  */
 14804       clear_mouse_face (hlinfo);
 14805       return;
 14806     }
 14807   else if (rc == 0)
 14808     /* On same tab-bar item as before.  */
 14809     goto set_help_echo;
 14810 
 14811   clear_mouse_face (hlinfo);
 14812 
 14813   bool mouse_down_p = false;
 14814   /* Mouse is down, but on different tab-bar item?  Or alternatively,
 14815      the mouse might've been pressed somewhere we don't know about,
 14816      and then have moved onto the tab bar.  In this case,
 14817      last_tab_bar_item is -1, so we DTRT and behave like other
 14818      programs by displaying the item as sunken. */
 14819   Display_Info *dpyinfo = FRAME_DISPLAY_INFO (f);
 14820   mouse_down_p = (gui_mouse_grabbed (dpyinfo)
 14821                   && f == dpyinfo->last_mouse_frame);
 14822 
 14823   if (mouse_down_p && f->last_tab_bar_item != prop_idx
 14824       && f->last_tab_bar_item != -1)
 14825     return;
 14826   draw = mouse_down_p ? DRAW_IMAGE_SUNKEN : DRAW_IMAGE_RAISED;
 14827 
 14828   /* If tab-bar item is not enabled, don't highlight it.  */
 14829   enabled_p = AREF (f->tab_bar_items, prop_idx + TAB_BAR_ITEM_ENABLED_P);
 14830   if (!NILP (enabled_p) && !NILP (Vmouse_highlight))
 14831     {
 14832       /* Compute the x-position of the glyph.  In front and past the
 14833          image is a space.  We include this in the highlighted area.  */
 14834       row = MATRIX_ROW (w->current_matrix, vpos);
 14835       for (i = x = 0; i < hpos; ++i)
 14836         x += row->glyphs[TEXT_AREA][i].pixel_width;
 14837 
 14838       /* Record this as the current active region.  */
 14839       hlinfo->mouse_face_beg_col = hpos;
 14840       hlinfo->mouse_face_beg_row = vpos;
 14841       hlinfo->mouse_face_beg_x = x;
 14842       hlinfo->mouse_face_past_end = false;
 14843 
 14844       hlinfo->mouse_face_end_col = hpos + 1;
 14845       hlinfo->mouse_face_end_row = vpos;
 14846       hlinfo->mouse_face_end_x = x + glyph->pixel_width;
 14847       hlinfo->mouse_face_window = window;
 14848       hlinfo->mouse_face_face_id = TAB_BAR_FACE_ID;
 14849 
 14850       /* Display it as active.  */
 14851       show_mouse_face (hlinfo, draw);
 14852     }
 14853 
 14854  set_help_echo:
 14855 
 14856   /* Set help_echo_string to a help string to display for this tab-bar item.
 14857      XTread_socket does the rest.  */
 14858   help_echo_object = help_echo_window = Qnil;
 14859   help_echo_pos = -1;
 14860   help_echo_string = AREF (f->tab_bar_items, prop_idx + TAB_BAR_ITEM_HELP);
 14861   if (NILP (help_echo_string))
 14862     help_echo_string = AREF (f->tab_bar_items, prop_idx + TAB_BAR_ITEM_CAPTION);
 14863 }
 14864 
 14865 #endif /* HAVE_WINDOW_SYSTEM */
 14866 
 14867 /* Find the tab-bar item at X coordinate and return its information.  */
 14868 static Lisp_Object
 14869 tty_get_tab_bar_item (struct frame *f, int x, int *prop_idx, bool *close_p)
 14870 {
 14871   ptrdiff_t clen = 0;
 14872 
 14873   for (int i = 0; i < f->n_tab_bar_items; i++)
 14874     {
 14875       Lisp_Object caption = AREF (f->tab_bar_items, (i * TAB_BAR_ITEM_NSLOTS
 14876                                                      + TAB_BAR_ITEM_CAPTION));
 14877       if (NILP (caption))
 14878         return Qnil;
 14879       clen += SCHARS (caption);
 14880       if (x < clen)
 14881         {
 14882           *prop_idx = i;
 14883           *close_p = !NILP (Fget_text_property (make_fixnum (SCHARS (caption)
 14884                                                              - (clen - x)),
 14885                                                 Qclose_tab,
 14886                                                 caption));
 14887           return caption;
 14888         }
 14889     }
 14890   return Qnil;
 14891 }
 14892 
 14893 /* Handle a mouse click at X/Y on the tab bar of TTY frame F.  If the
 14894    click was on the tab bar and was handled, populate the EVENT
 14895    structure, store it in keyboard queue, and return true; otherwise
 14896    return false.  MODIFIERS are event modifiers for generating the tab
 14897    release event.  */
 14898 Lisp_Object
 14899 tty_handle_tab_bar_click (struct frame *f, int x, int y, bool down_p,
 14900                           struct input_event *event)
 14901 {
 14902   /* Did they click on the tab bar?  */
 14903   if (y < FRAME_MENU_BAR_LINES (f)
 14904       || y >= FRAME_MENU_BAR_LINES (f) + FRAME_TAB_BAR_LINES (f))
 14905     return Qnil;
 14906 
 14907   /* Find the tab-bar item where the X,Y coordinates belong.  */
 14908   int prop_idx;
 14909   bool close_p;
 14910   Lisp_Object caption = tty_get_tab_bar_item (f, x, &prop_idx, &close_p);
 14911 
 14912   if (NILP (caption))
 14913     return Qnil;
 14914 
 14915   if (NILP (AREF (f->tab_bar_items,
 14916                   prop_idx * TAB_BAR_ITEM_NSLOTS + TAB_BAR_ITEM_ENABLED_P)))
 14917     return Qnil;
 14918 
 14919   if (down_p)
 14920     f->last_tab_bar_item = prop_idx;
 14921   else
 14922     f->last_tab_bar_item = -1;
 14923 
 14924   caption = Fcopy_sequence (caption);
 14925 
 14926   AUTO_LIST2 (props, Qmenu_item,
 14927               list3 (AREF (f->tab_bar_items, prop_idx * TAB_BAR_ITEM_NSLOTS
 14928                            + TAB_BAR_ITEM_KEY),
 14929                      AREF (f->tab_bar_items, prop_idx * TAB_BAR_ITEM_NSLOTS
 14930                            + TAB_BAR_ITEM_BINDING),
 14931                      close_p ? Qt : Qnil));
 14932 
 14933   Fadd_text_properties (make_fixnum (0), make_fixnum (SCHARS (caption)),
 14934                         props, caption);
 14935 
 14936   return Fcons (Qtab_bar, Fcons (caption, make_fixnum (0)));
 14937 }
 14938 
 14939 
 14940 
 14941 /***********************************************************************
 14942                                Tool-bars
 14943  ***********************************************************************/
 14944 
 14945 #ifdef HAVE_WINDOW_SYSTEM
 14946 
 14947 /* Update the tool-bar item list for frame F.  This has to be done
 14948    before we start to fill in any display lines.  Called from
 14949    prepare_menu_bars.  If SAVE_MATCH_DATA, we must save
 14950    and restore it here.  */
 14951 
 14952 static void
 14953 update_tool_bar (struct frame *f, bool save_match_data)
 14954 {
 14955 #ifdef HAVE_EXT_TOOL_BAR
 14956   bool do_update = FRAME_EXTERNAL_TOOL_BAR (f);
 14957 #else
 14958   bool do_update = (WINDOWP (f->tool_bar_window)
 14959                     && WINDOW_TOTAL_LINES (XWINDOW (f->tool_bar_window)) > 0);
 14960 #endif
 14961 
 14962   if (do_update)
 14963     {
 14964       Lisp_Object window;
 14965       struct window *w;
 14966 
 14967       window = FRAME_SELECTED_WINDOW (f);
 14968       w = XWINDOW (window);
 14969 
 14970       /* If the user has switched buffers or windows, we need to
 14971          recompute to reflect the new bindings.  But we'll
 14972          recompute when update_mode_lines is set too; that means
 14973          that people can use force-mode-line-update to request
 14974          that the menu bar be recomputed.  The adverse effect on
 14975          the rest of the redisplay algorithm is about the same as
 14976          windows_or_buffers_changed anyway.  */
 14977       if (windows_or_buffers_changed
 14978           || w->update_mode_line
 14979           || update_mode_lines
 14980           || window_buffer_changed (w))
 14981         {
 14982           struct buffer *prev = current_buffer;
 14983           specpdl_ref count = SPECPDL_INDEX ();
 14984           Lisp_Object frame, new_tool_bar;
 14985           int new_n_tool_bar;
 14986 
 14987           /* Set current_buffer to the buffer of the selected
 14988              window of the frame, so that we get the right local
 14989              keymaps.  */
 14990           set_buffer_internal_1 (XBUFFER (w->contents));
 14991 
 14992           /* Save match data, if we must.  */
 14993           if (save_match_data)
 14994             record_unwind_save_match_data ();
 14995 
 14996           /* Make sure that we don't accidentally use bogus keymaps.  */
 14997           if (NILP (Voverriding_local_map_menu_flag))
 14998             {
 14999               specbind (Qoverriding_terminal_local_map, Qnil);
 15000               specbind (Qoverriding_local_map, Qnil);
 15001             }
 15002 
 15003           /* We must temporarily set the selected frame to this frame
 15004              before calling tool_bar_items, because the calculation of
 15005              the tool-bar keymap uses the selected frame (see
 15006              `tool-bar-make-keymap' in tool-bar.el).  */
 15007           eassert (EQ (selected_window,
 15008                        /* Since we only explicitly preserve selected_frame,
 15009                           check that selected_window would be redundant.  */
 15010                        XFRAME (selected_frame)->selected_window));
 15011           record_unwind_protect (restore_selected_window, selected_window);
 15012           XSETFRAME (frame, f);
 15013           selected_frame = frame;
 15014           selected_window = FRAME_SELECTED_WINDOW (f);
 15015 
 15016           /* Build desired tool-bar items from keymaps.  */
 15017           new_tool_bar
 15018             = tool_bar_items (Fcopy_sequence (f->tool_bar_items),
 15019                               &new_n_tool_bar);
 15020 
 15021           /* Redisplay the tool-bar if we changed it.  */
 15022           if (new_n_tool_bar != f->n_tool_bar_items
 15023               || NILP (Fequal (new_tool_bar, f->tool_bar_items)))
 15024             {
 15025               /* Redisplay that happens asynchronously due to an expose event
 15026                  may access f->tool_bar_items.  Make sure we update both
 15027                  variables within BLOCK_INPUT so no such event interrupts.  */
 15028               block_input ();
 15029               fset_tool_bar_items (f, new_tool_bar);
 15030               f->n_tool_bar_items = new_n_tool_bar;
 15031               w->update_mode_line = true;
 15032               unblock_input ();
 15033             }
 15034 
 15035           unbind_to (count, Qnil);
 15036           set_buffer_internal_1 (prev);
 15037         }
 15038     }
 15039 }
 15040 
 15041 #ifndef HAVE_EXT_TOOL_BAR
 15042 
 15043 /* Set F->desired_tool_bar_string to a Lisp string representing frame
 15044    F's desired tool-bar contents.  F->tool_bar_items must have
 15045    been set up previously by calling prepare_menu_bars.
 15046 
 15047    Also set F->tool_bar_wraps_p to whether or not the tool bar
 15048    contains explicit line breaking items.  */
 15049 
 15050 static void
 15051 build_desired_tool_bar_string (struct frame *f)
 15052 {
 15053   int i, size, size_needed;
 15054   Lisp_Object image, plist;
 15055 
 15056   image = plist = Qnil;
 15057 
 15058   /* Prepare F->desired_tool_bar_string.  If we can reuse it, do so.
 15059      Otherwise, make a new string.  */
 15060 
 15061   /* The size of the string we might be able to reuse.  */
 15062   size = (STRINGP (f->desired_tool_bar_string)
 15063           ? SCHARS (f->desired_tool_bar_string)
 15064           : 0);
 15065 
 15066   /* We need one space in the string for each image.  */
 15067   size_needed = f->n_tool_bar_items;
 15068 
 15069   /* Reuse f->desired_tool_bar_string, if possible.  */
 15070 
 15071   if (size < size_needed || NILP (f->desired_tool_bar_string))
 15072     /* Don't initialize the contents of this string yet, as they will
 15073        be set within the loop below.  */
 15074     fset_desired_tool_bar_string (f, make_uninit_string (size_needed));
 15075   else
 15076     {
 15077       AUTO_LIST4 (props, Qdisplay, Qnil, Qmenu_item, Qnil);
 15078       Fremove_text_properties (make_fixnum (0), make_fixnum (size),
 15079                                props, f->desired_tool_bar_string);
 15080     }
 15081 
 15082   f->tool_bar_wraps_p = false;
 15083 
 15084   /* Put a `display' property on the string for the images to display,
 15085      put a `menu_item' property on tool-bar items with a value that
 15086      is the index of the item in F's tool-bar item vector.  */
 15087   for (i = 0; i < f->n_tool_bar_items; ++i)
 15088     {
 15089 #define PROP(IDX) \
 15090   AREF (f->tool_bar_items, i * TOOL_BAR_ITEM_NSLOTS + (IDX))
 15091 
 15092       bool enabled_p = !NILP (PROP (TOOL_BAR_ITEM_ENABLED_P));
 15093       bool selected_p = !NILP (PROP (TOOL_BAR_ITEM_SELECTED_P));
 15094       int hmargin, vmargin, relief, idx, end;
 15095 
 15096       if (!NILP (PROP (TOOL_BAR_ITEM_WRAP)))
 15097         {
 15098           /* This is a line wrap.  Instead of building a tool bar
 15099              item, display a new line character instead.  */
 15100           SSET (f->desired_tool_bar_string, i, '\n');
 15101 
 15102           /* Set F->tool_bar_wraps_p.  This tells redisplay_tool_bar
 15103              to allow individual rows to be different heights.  */
 15104           f->tool_bar_wraps_p = true;
 15105           continue;
 15106         }
 15107 
 15108       /* Replace this with a space character.  */
 15109       SSET (f->desired_tool_bar_string, i, ' ');
 15110 
 15111       /* If image is a vector, choose the image according to the
 15112          button state.  */
 15113       image = PROP (TOOL_BAR_ITEM_IMAGES);
 15114       if (VECTORP (image))
 15115         {
 15116           if (enabled_p)
 15117             idx = (selected_p
 15118                    ? TOOL_BAR_IMAGE_ENABLED_SELECTED
 15119                    : TOOL_BAR_IMAGE_ENABLED_DESELECTED);
 15120           else
 15121             idx = (selected_p
 15122                    ? TOOL_BAR_IMAGE_DISABLED_SELECTED
 15123                    : TOOL_BAR_IMAGE_DISABLED_DESELECTED);
 15124 
 15125           eassert (ASIZE (image) >= idx);
 15126           image = AREF (image, idx);
 15127         }
 15128       else
 15129         idx = -1;
 15130 
 15131       /* Ignore invalid image specifications.  */
 15132       if (!valid_image_p (image))
 15133         continue;
 15134 
 15135       /* Display the tool-bar button pressed, or depressed.  */
 15136       plist = Fcopy_sequence (XCDR (image));
 15137 
 15138       /* Compute margin and relief to draw.  */
 15139       relief = (tool_bar_button_relief >= 0
 15140                 ? min (tool_bar_button_relief,
 15141                        min (INT_MAX, MOST_POSITIVE_FIXNUM))
 15142                 : DEFAULT_TOOL_BAR_BUTTON_RELIEF);
 15143       hmargin = vmargin = relief;
 15144 
 15145       if (RANGED_FIXNUMP (1, Vtool_bar_button_margin,
 15146                            INT_MAX - max (hmargin, vmargin)))
 15147         {
 15148           hmargin += XFIXNAT (Vtool_bar_button_margin);
 15149           vmargin += XFIXNAT (Vtool_bar_button_margin);
 15150         }
 15151       else if (CONSP (Vtool_bar_button_margin))
 15152         {
 15153           if (RANGED_FIXNUMP (1, XCAR (Vtool_bar_button_margin),
 15154                                INT_MAX - hmargin))
 15155             hmargin += XFIXNAT (XCAR (Vtool_bar_button_margin));
 15156 
 15157           if (RANGED_FIXNUMP (1, XCDR (Vtool_bar_button_margin),
 15158                                INT_MAX - vmargin))
 15159             vmargin += XFIXNAT (XCDR (Vtool_bar_button_margin));
 15160         }
 15161 
 15162       if (auto_raise_tool_bar_buttons_p)
 15163         {
 15164           /* Add a `:relief' property to the image spec if the item is
 15165              selected.  */
 15166           if (selected_p)
 15167             {
 15168               plist = plist_put (plist, QCrelief, make_fixnum (-relief));
 15169               hmargin -= relief;
 15170               vmargin -= relief;
 15171             }
 15172         }
 15173       else
 15174         {
 15175           /* If image is selected, display it pressed, i.e. with a
 15176              negative relief.  If it's not selected, display it with a
 15177              raised relief.  */
 15178           plist = plist_put (plist, QCrelief,
 15179                              (selected_p
 15180                               ? make_fixnum (-relief)
 15181                               : make_fixnum (relief)));
 15182           hmargin -= relief;
 15183           vmargin -= relief;
 15184         }
 15185 
 15186       /* Put a margin around the image.  */
 15187       if (hmargin || vmargin)
 15188         {
 15189           if (hmargin == vmargin)
 15190             plist = plist_put (plist, QCmargin, make_fixnum (hmargin));
 15191           else
 15192             plist = plist_put (plist, QCmargin,
 15193                                Fcons (make_fixnum (hmargin),
 15194                                       make_fixnum (vmargin)));
 15195         }
 15196 
 15197       /* If button is not enabled, and we don't have special images
 15198          for the disabled state, make the image appear disabled by
 15199          applying an appropriate algorithm to it.  */
 15200       if (!enabled_p && idx < 0)
 15201         plist = plist_put (plist, QCconversion, Qdisabled);
 15202 
 15203       /* Put a `display' text property on the string for the image to
 15204          display.  Put a `menu-item' property on the string that gives
 15205          the start of this item's properties in the tool-bar items
 15206          vector.  */
 15207       image = Fcons (Qimage, plist);
 15208       AUTO_LIST4 (props, Qdisplay, image, Qmenu_item,
 15209                   make_fixnum (i * TOOL_BAR_ITEM_NSLOTS));
 15210 
 15211       /* Let the last image hide all remaining spaces in the tool bar
 15212          string.  The string can be longer than needed when we reuse a
 15213          previous string.  */
 15214       if (i + 1 == f->n_tool_bar_items)
 15215         end = SCHARS (f->desired_tool_bar_string);
 15216       else
 15217         end = i + 1;
 15218       Fadd_text_properties (make_fixnum (i), make_fixnum (end),
 15219                             props, f->desired_tool_bar_string);
 15220 #undef PROP
 15221     }
 15222 
 15223   /* Now replace each character between i and the end of the tool bar
 15224      string with spaces, to prevent stray newlines from accumulating
 15225      when the number of tool bar items decreases.  `size' is 0 if the
 15226      tool bar string is new, but in that case the string will have
 15227      been completely initialized anyway.  */
 15228 
 15229   for (; i < size; ++i)
 15230     /* Replace this with a space character.  */
 15231     SSET (f->desired_tool_bar_string, i, ' ');
 15232 }
 15233 
 15234 
 15235 /* Display one line of the tool-bar of frame IT->f.
 15236 
 15237    HEIGHT specifies the desired height of the tool-bar line.
 15238    If the actual height of the glyph row is less than HEIGHT, the
 15239    row's height is increased to HEIGHT, and the icons are centered
 15240    vertically in the new height.
 15241 
 15242    If HEIGHT is -1, we are counting needed tool-bar lines, so don't
 15243    count a final empty row in case the tool-bar width exactly matches
 15244    the window width.
 15245 
 15246    HEIGHT may also be -1 if there is an explicit line wrapping item
 15247    inside the tool bar; in that case, allow individual rows of the
 15248    tool bar to differ in height.  */
 15249 
 15250 static void
 15251 display_tool_bar_line (struct it *it, int height)
 15252 {
 15253   struct glyph_row *row = it->glyph_row;
 15254   int max_x = it->last_visible_x;
 15255   struct glyph *last;
 15256 
 15257   /* Don't extend on a previously drawn tool bar items (Bug#16058).  */
 15258   clear_glyph_row (row);
 15259   row->enabled_p = true;
 15260   row->y = it->current_y;
 15261 
 15262   /* Note that this isn't made use of if the face hasn't a box,
 15263      so there's no need to check the face here.  */
 15264   it->start_of_box_run_p = true;
 15265 
 15266   while (it->current_x < max_x)
 15267     {
 15268       int x, n_glyphs_before, i, nglyphs;
 15269       struct it it_before;
 15270 
 15271       /* Get the next display element.  */
 15272       if (!get_next_display_element (it))
 15273         {
 15274           /* Don't count empty row if we are counting needed tool-bar lines.  */
 15275           if (height < 0 && !it->hpos)
 15276             return;
 15277           break;
 15278         }
 15279 
 15280       /* Produce glyphs.  */
 15281       n_glyphs_before = row->used[TEXT_AREA];
 15282       it_before = *it;
 15283 
 15284       PRODUCE_GLYPHS (it);
 15285 
 15286       nglyphs = row->used[TEXT_AREA] - n_glyphs_before;
 15287       i = 0;
 15288       x = it_before.current_x;
 15289       while (i < nglyphs)
 15290         {
 15291           struct glyph *glyph = row->glyphs[TEXT_AREA] + n_glyphs_before + i;
 15292 
 15293           if (x + glyph->pixel_width > max_x)
 15294             {
 15295               /* Glyph doesn't fit on line.  Backtrack.  */
 15296               row->used[TEXT_AREA] = n_glyphs_before;
 15297               *it = it_before;
 15298               /* If this is the only glyph on this line, it will never fit on the
 15299                  tool-bar, so skip it.  But ensure there is at least one glyph,
 15300                  so we don't accidentally disable the tool-bar.  */
 15301               if (n_glyphs_before == 0
 15302                   && (it->vpos > 0 || IT_STRING_CHARPOS (*it) < it->end_charpos-1))
 15303                 break;
 15304               goto out;
 15305             }
 15306 
 15307           ++it->hpos;
 15308           x += glyph->pixel_width;
 15309           ++i;
 15310         }
 15311 
 15312       /* Stop at the end of the iterator, and move to the next line
 15313          upon a '\n' appearing in the tool bar string.  Tool bar
 15314          strings may contain multiple new line characters when
 15315          explicit wrap items are encountered.  */
 15316 
 15317       if (ITERATOR_AT_END_OF_LINE_P (it))
 15318         {
 15319           reseat_at_next_visible_line_start (it, false);
 15320           break;
 15321         }
 15322 
 15323       if (ITERATOR_AT_END_P (it))
 15324         break;
 15325 
 15326       set_iterator_to_next (it, true);
 15327     }
 15328 
 15329  out:;
 15330 
 15331   row->displays_text_p = row->used[TEXT_AREA] != 0;
 15332 
 15333   /* Use default face for the border below the tool bar.
 15334 
 15335      FIXME: When auto-resize-tool-bars is grow-only, there is
 15336      no additional border below the possibly empty tool-bar lines.
 15337      So to make the extra empty lines look "normal", we have to
 15338      use the tool-bar face for the border too.  */
 15339   if (!MATRIX_ROW_DISPLAYS_TEXT_P (row)
 15340       && !EQ (Vauto_resize_tool_bars, Qgrow_only))
 15341     it->face_id = DEFAULT_FACE_ID;
 15342 
 15343   extend_face_to_end_of_line (it);
 15344   last = row->glyphs[TEXT_AREA] + row->used[TEXT_AREA] - 1;
 15345   last->right_box_line_p = true;
 15346   if (last == row->glyphs[TEXT_AREA])
 15347     last->left_box_line_p = true;
 15348 
 15349   /* Make line the desired height and center it vertically.  */
 15350   if (height != -1
 15351       && (height -= it->max_ascent + it->max_descent) > 0)
 15352     {
 15353       /* Don't add more than one line height.  */
 15354       height %= FRAME_LINE_HEIGHT (it->f);
 15355       it->max_ascent += height / 2;
 15356       it->max_descent += (height + 1) / 2;
 15357     }
 15358 
 15359   compute_line_metrics (it);
 15360 
 15361   /* If line is empty, make it occupy the rest of the tool-bar.  */
 15362   if (!MATRIX_ROW_DISPLAYS_TEXT_P (row))
 15363     {
 15364       row->height = row->phys_height = it->last_visible_y - row->y;
 15365       row->visible_height = row->height;
 15366       row->ascent = row->phys_ascent = 0;
 15367       row->extra_line_spacing = 0;
 15368     }
 15369 
 15370   row->full_width_p = true;
 15371   row->continued_p = false;
 15372   row->truncated_on_left_p = false;
 15373   row->truncated_on_right_p = false;
 15374 
 15375   it->current_x = it->hpos = 0;
 15376   it->current_y += row->height;
 15377   ++it->vpos;
 15378   ++it->glyph_row;
 15379 }
 15380 
 15381 
 15382 /* Value is the number of pixels needed to make all tool-bar items of
 15383    frame F visible.  The actual number of glyph rows needed is
 15384    returned in *N_ROWS if non-NULL.  */
 15385 
 15386 static int
 15387 tool_bar_height (struct frame *f, int *n_rows, bool pixelwise)
 15388 {
 15389   struct window *w = XWINDOW (f->tool_bar_window);
 15390   struct it it;
 15391   /* tool_bar_height is called from redisplay_tool_bar after building
 15392      the desired matrix, so use (unused) mode-line row as temporary row to
 15393      avoid destroying the first tool-bar row.  */
 15394   struct glyph_row *temp_row = MATRIX_MODE_LINE_ROW (w->desired_matrix);
 15395 
 15396   /* Initialize an iterator for iteration over
 15397      F->desired_tool_bar_string in the tool-bar window of frame F.  */
 15398   init_iterator (&it, w, -1, -1, temp_row, TOOL_BAR_FACE_ID);
 15399   temp_row->reversed_p = false;
 15400   it.first_visible_x = 0;
 15401   it.last_visible_x = WINDOW_PIXEL_WIDTH (w);
 15402   reseat_to_string (&it, NULL, f->desired_tool_bar_string,
 15403                     0, 0, 0, STRING_MULTIBYTE (f->desired_tool_bar_string));
 15404   it.paragraph_embedding = L2R;
 15405 
 15406   while (!ITERATOR_AT_END_P (&it))
 15407     {
 15408       clear_glyph_row (temp_row);
 15409       it.glyph_row = temp_row;
 15410       display_tool_bar_line (&it, -1);
 15411     }
 15412   clear_glyph_row (temp_row);
 15413 
 15414   /* f->n_tool_bar_rows == 0 means "unknown"; -1 means no tool-bar.  */
 15415   if (n_rows)
 15416     *n_rows = it.vpos > 0 ? it.vpos : -1;
 15417 
 15418   if (pixelwise)
 15419     return it.current_y;
 15420   else
 15421     return (it.current_y + FRAME_LINE_HEIGHT (f) - 1) / FRAME_LINE_HEIGHT (f);
 15422 }
 15423 
 15424 #endif /* ! (HAVE_EXT_TOOL_BAR) */
 15425 
 15426 DEFUN ("tool-bar-height", Ftool_bar_height, Stool_bar_height,
 15427        0, 2, 0,
 15428        doc: /* Return the number of lines occupied by the tool bar of FRAME.
 15429 If FRAME is nil or omitted, use the selected frame.  Optional argument
 15430 PIXELWISE non-nil means return the height of the tool bar in pixels.  */)
 15431   (Lisp_Object frame, Lisp_Object pixelwise)
 15432 {
 15433   int height = 0;
 15434 
 15435 #ifndef HAVE_EXT_TOOL_BAR
 15436   struct frame *f = decode_any_frame (frame);
 15437 
 15438   if (WINDOWP (f->tool_bar_window)
 15439       && WINDOW_PIXEL_HEIGHT (XWINDOW (f->tool_bar_window)) > 0)
 15440     {
 15441       update_tool_bar (f, true);
 15442       if (f->n_tool_bar_items)
 15443         {
 15444           build_desired_tool_bar_string (f);
 15445           height = tool_bar_height (f, NULL, !NILP (pixelwise));
 15446         }
 15447     }
 15448 #endif
 15449 
 15450   return make_fixnum (height);
 15451 }
 15452 
 15453 #ifndef HAVE_EXT_TOOL_BAR
 15454 
 15455 /* Display the internal tool-bar of frame F.  Value is true if
 15456    tool-bar's height should be changed.  */
 15457 static bool
 15458 redisplay_tool_bar (struct frame *f)
 15459 {
 15460   struct window *w;
 15461   struct it it;
 15462   struct glyph_row *row;
 15463   bool change_height_p;
 15464 
 15465   change_height_p = false;
 15466   f->tool_bar_redisplayed = true;
 15467 
 15468   /* If frame hasn't a tool-bar window or if it is zero-height, don't
 15469      do anything.  This means you must start with tool-bar-lines
 15470      non-zero to get the auto-sizing effect.  Or in other words, you
 15471      can turn off tool-bars by specifying tool-bar-lines zero.  */
 15472   if (!WINDOWP (f->tool_bar_window)
 15473       || (w = XWINDOW (f->tool_bar_window),
 15474           WINDOW_TOTAL_LINES (w) == 0))
 15475     {
 15476       /* Even if we do not display a tool bar initially, still pretend
 15477          that we have resized it already.  This avoids that a later
 15478          activation of the tool bar resizes the frame, despite of the
 15479          fact that a setting of 'frame-inhibit-implied-resize' should
 15480          inhibit it (Bug#52986).  */
 15481       f->tool_bar_resized = true;
 15482 
 15483       return false;
 15484     }
 15485 
 15486   /* Set up an iterator for the tool-bar window.  */
 15487   init_iterator (&it, w, -1, -1, w->desired_matrix->rows, TOOL_BAR_FACE_ID);
 15488   it.first_visible_x = 0;
 15489   it.last_visible_x = WINDOW_PIXEL_WIDTH (w);
 15490   row = it.glyph_row;
 15491   row->reversed_p = false;
 15492 
 15493   /* Build a string that represents the contents of the tool-bar.  */
 15494   build_desired_tool_bar_string (f);
 15495   reseat_to_string (&it, NULL, f->desired_tool_bar_string,
 15496                     0, 0, 0, STRING_MULTIBYTE (f->desired_tool_bar_string));
 15497   /* FIXME: This should be controlled by a user option.  But it
 15498      doesn't make sense to have an R2L tool bar if the menu bar cannot
 15499      be drawn also R2L, and making the menu bar R2L is tricky due to
 15500      toolkit-specific code that implements it.  If an R2L tool bar is
 15501      ever supported, display_tool_bar_line should also be augmented to
 15502      call unproduce_glyphs like display_line and display_string
 15503      do.  */
 15504   it.paragraph_embedding = L2R;
 15505 
 15506   if (f->n_tool_bar_rows == 0)
 15507     {
 15508       int new_height = tool_bar_height (f, &f->n_tool_bar_rows, true);
 15509 
 15510       if (new_height != WINDOW_PIXEL_HEIGHT (w))
 15511         {
 15512           if (FRAME_TERMINAL (f)->change_tool_bar_height_hook)
 15513             FRAME_TERMINAL (f)->change_tool_bar_height_hook (f, new_height);
 15514           frame_default_tool_bar_height = new_height;
 15515           /* Always do that now.  */
 15516           clear_glyph_matrix (w->desired_matrix);
 15517           f->fonts_changed = true;
 15518 
 15519           /* Kludge (this applies to the X Windows version as well as
 15520              Android): when the tool bar size changes,
 15521              adjust_window_size (presumably called by
 15522              change_tool_bar_height_hook) does not call through to
 15523              resize_frame_windows.  Pending further investigation,
 15524              just call it here as well.  */
 15525           resize_frame_windows (f, FRAME_INNER_HEIGHT (f), false);
 15526 
 15527           return true;
 15528         }
 15529     }
 15530 
 15531   /* Display as many lines as needed to display all tool-bar items.  */
 15532 
 15533   if (f->n_tool_bar_rows > 0)
 15534     {
 15535       int border, rows, height, extra;
 15536 
 15537       if (TYPE_RANGED_FIXNUMP (int, Vtool_bar_border))
 15538         border = XFIXNUM (Vtool_bar_border);
 15539       else if (EQ (Vtool_bar_border, Qinternal_border_width))
 15540         border = FRAME_INTERNAL_BORDER_WIDTH (f);
 15541       else if (EQ (Vtool_bar_border, Qborder_width))
 15542         border = f->border_width;
 15543       else
 15544         border = 0;
 15545       if (border < 0)
 15546         border = 0;
 15547 
 15548       rows = f->n_tool_bar_rows;
 15549 
 15550       if (f->tool_bar_wraps_p)
 15551         {
 15552           /* If the tool bar contains explicit line wrapping items,
 15553              don't force each row to have a fixed height.  */
 15554 
 15555           while (!ITERATOR_AT_END_P (&it))
 15556             display_tool_bar_line (&it, -1);
 15557 
 15558           /* Because changes to individual tool bar items may now
 15559              change the height of the tool bar, adjust the height of
 15560              the tool bar window if it is different from the tool bar
 15561              height in any way.  */
 15562 
 15563           if (it.current_y != it.last_visible_y)
 15564             change_height_p = true;
 15565         }
 15566       else
 15567         {
 15568           height = max (1, (it.last_visible_y - border) / rows);
 15569           extra = it.last_visible_y - border - height * rows;
 15570 
 15571           while (it.current_y < it.last_visible_y)
 15572             {
 15573               int h = 0;
 15574               if (extra > 0 && rows-- > 0)
 15575                 {
 15576                   h = (extra + rows - 1) / rows;
 15577                   extra -= h;
 15578                 }
 15579           
 15580               display_tool_bar_line (&it, height + h);
 15581             }
 15582         }
 15583     }
 15584   else
 15585     {
 15586       while (it.current_y < it.last_visible_y)
 15587         display_tool_bar_line (&it, 0);
 15588     }
 15589 
 15590   /* It doesn't make much sense to try scrolling in the tool-bar
 15591      window, so don't do it.  */
 15592   w->desired_matrix->no_scrolling_p = true;
 15593   w->must_be_updated_p = true;
 15594 
 15595   if (!NILP (Vauto_resize_tool_bars))
 15596     {
 15597       /* If we couldn't display everything, change the tool-bar's
 15598          height if there is room for more.  */
 15599       if (IT_STRING_CHARPOS (it) < it.end_charpos)
 15600         change_height_p = true;
 15601 
 15602       /* We subtract 1 because display_tool_bar_line advances the
 15603          glyph_row pointer before returning to its caller.  We want to
 15604          examine the last glyph row produced by
 15605          display_tool_bar_line.  */
 15606       row = it.glyph_row - 1;
 15607 
 15608       /* If there are blank lines at the end, except for a partially
 15609          visible blank line at the end that is smaller than
 15610          FRAME_LINE_HEIGHT, change the tool-bar's height.  */
 15611       if (!MATRIX_ROW_DISPLAYS_TEXT_P (row)
 15612           && row->height >= FRAME_LINE_HEIGHT (f))
 15613         change_height_p = true;
 15614 
 15615       /* If row displays tool-bar items, but is partially visible,
 15616          change the tool-bar's height.  */
 15617       if (MATRIX_ROW_DISPLAYS_TEXT_P (row)
 15618           && MATRIX_ROW_BOTTOM_Y (row) > it.last_visible_y)
 15619         change_height_p = true;
 15620 
 15621       /* Resize windows as needed by changing the `tool-bar-lines'
 15622          frame parameter.  */
 15623       if (change_height_p)
 15624         {
 15625           int nrows;
 15626           int new_height = tool_bar_height (f, &nrows, true);
 15627 
 15628           change_height_p = ((EQ (Vauto_resize_tool_bars, Qgrow_only)
 15629                               && !f->minimize_tool_bar_window_p)
 15630                              ? (new_height > WINDOW_PIXEL_HEIGHT (w))
 15631                              : (new_height != WINDOW_PIXEL_HEIGHT (w)));
 15632           f->minimize_tool_bar_window_p = false;
 15633 
 15634           if (change_height_p)
 15635             {
 15636               if (FRAME_TERMINAL (f)->change_tool_bar_height_hook)
 15637                 FRAME_TERMINAL (f)->change_tool_bar_height_hook (f, new_height);
 15638               frame_default_tool_bar_height = new_height;
 15639               clear_glyph_matrix (w->desired_matrix);
 15640               f->n_tool_bar_rows = nrows;
 15641               f->fonts_changed = true;
 15642 
 15643               return true;
 15644             }
 15645         }
 15646     }
 15647 
 15648   f->minimize_tool_bar_window_p = false;
 15649 
 15650   return false;
 15651 }
 15652 
 15653 /* Get information about the tool-bar item which is displayed in GLYPH
 15654    on frame F.  Return in *PROP_IDX the index where tool-bar item
 15655    properties start in F->tool_bar_items.  Value is false if
 15656    GLYPH doesn't display a tool-bar item.  */
 15657 
 15658 static bool
 15659 tool_bar_item_info (struct frame *f, struct glyph *glyph, int *prop_idx)
 15660 {
 15661   Lisp_Object prop;
 15662   ptrdiff_t charpos;
 15663 
 15664   /* This function can be called asynchronously, which means we must
 15665      exclude any possibility that Fget_text_property signals an
 15666      error.  */
 15667   charpos = min (SCHARS (f->current_tool_bar_string), glyph->charpos);
 15668   charpos = max (0, charpos);
 15669 
 15670   /* Get the text property `menu-item' at pos. The value of that
 15671      property is the start index of this item's properties in
 15672      F->tool_bar_items.  */
 15673   prop = Fget_text_property (make_fixnum (charpos),
 15674                              Qmenu_item, f->current_tool_bar_string);
 15675   if (! FIXNUMP (prop))
 15676     return false;
 15677   *prop_idx = XFIXNUM (prop);
 15678   return true;
 15679 }
 15680 
 15681 
 15682 /* Get information about the tool-bar item at position X/Y on frame F.
 15683    Return in *GLYPH a pointer to the glyph of the tool-bar item in
 15684    the current matrix of the tool-bar window of F, or NULL if not
 15685    on a tool-bar item.  Return in *PROP_IDX the index of the tool-bar
 15686    item in F->tool_bar_items.  Value is
 15687 
 15688    -1   if X/Y is not on a tool-bar item
 15689    0    if X/Y is on the same item that was highlighted before.
 15690    1    otherwise.  */
 15691 
 15692 static int
 15693 get_tool_bar_item (struct frame *f, int x, int y, struct glyph **glyph,
 15694                    int *hpos, int *vpos, int *prop_idx)
 15695 {
 15696   Mouse_HLInfo *hlinfo = MOUSE_HL_INFO (f);
 15697   struct window *w = XWINDOW (f->tool_bar_window);
 15698   int area;
 15699 
 15700   /* Find the glyph under X/Y.  */
 15701   *glyph = x_y_to_hpos_vpos (w, x, y, hpos, vpos, 0, 0, &area);
 15702   if (*glyph == NULL)
 15703     return -1;
 15704 
 15705   /* Get the start of this tool-bar item's properties in
 15706      f->tool_bar_items.  */
 15707   if (!tool_bar_item_info (f, *glyph, prop_idx))
 15708     return -1;
 15709 
 15710   /* Is mouse on the highlighted item?  */
 15711   if (EQ (f->tool_bar_window, hlinfo->mouse_face_window)
 15712       && *vpos >= hlinfo->mouse_face_beg_row
 15713       && *vpos <= hlinfo->mouse_face_end_row
 15714       && (*vpos > hlinfo->mouse_face_beg_row
 15715           || *hpos >= hlinfo->mouse_face_beg_col)
 15716       && (*vpos < hlinfo->mouse_face_end_row
 15717           || *hpos < hlinfo->mouse_face_end_col
 15718           || hlinfo->mouse_face_past_end))
 15719     return 0;
 15720 
 15721   return 1;
 15722 }
 15723 
 15724 
 15725 /* EXPORT:
 15726    Handle mouse button event on the tool-bar of frame F, at
 15727    frame-relative coordinates X/Y.  DOWN_P is true for a button press,
 15728    false for button release.  MODIFIERS is event modifiers for button
 15729    release.  DEVICE is the device the click came from, or Qt.  */
 15730 
 15731 void
 15732 handle_tool_bar_click_with_device (struct frame *f, int x, int y, bool down_p,
 15733                                    int modifiers, Lisp_Object device)
 15734 {
 15735   Mouse_HLInfo *hlinfo = MOUSE_HL_INFO (f);
 15736   struct window *w = XWINDOW (f->tool_bar_window);
 15737   int hpos, vpos, prop_idx;
 15738   struct glyph *glyph;
 15739   Lisp_Object enabled_p;
 15740   int ts;
 15741 
 15742   /* If not on the highlighted tool-bar item, and mouse-highlight is
 15743      non-nil, return.  This is so we generate the tool-bar button
 15744      click only when the mouse button is released on the same item as
 15745      where it was pressed.  However, when mouse-highlight is disabled,
 15746      generate the click when the button is released regardless of the
 15747      highlight, since tool-bar items are not highlighted in that
 15748      case.  */
 15749   frame_to_window_pixel_xy (w, &x, &y);
 15750   ts = get_tool_bar_item (f, x, y, &glyph, &hpos, &vpos, &prop_idx);
 15751   if (ts == -1
 15752       || (ts != 0 && !NILP (Vmouse_highlight)))
 15753     return;
 15754 
 15755   /* When mouse-highlight is off, generate the click for the item
 15756      where the button was pressed, disregarding where it was
 15757      released.  */
 15758   if (NILP (Vmouse_highlight) && !down_p)
 15759     prop_idx = f->last_tool_bar_item;
 15760 
 15761   /* If item is disabled, do nothing.  */
 15762   enabled_p = AREF (f->tool_bar_items, prop_idx + TOOL_BAR_ITEM_ENABLED_P);
 15763   if (NILP (enabled_p))
 15764     return;
 15765 
 15766   if (down_p)
 15767     {
 15768       /* Show item in pressed state.  */
 15769       if (!NILP (Vmouse_highlight))
 15770         show_mouse_face (hlinfo, DRAW_IMAGE_SUNKEN);
 15771       f->last_tool_bar_item = prop_idx;
 15772     }
 15773   else
 15774     {
 15775       Lisp_Object key, frame;
 15776       struct input_event event;
 15777       EVENT_INIT (event);
 15778 
 15779       /* Show item in released state.  */
 15780       if (!NILP (Vmouse_highlight))
 15781         show_mouse_face (hlinfo, DRAW_IMAGE_RAISED);
 15782 
 15783       key = AREF (f->tool_bar_items, prop_idx + TOOL_BAR_ITEM_KEY);
 15784 
 15785       XSETFRAME (frame, f);
 15786       event.kind = TOOL_BAR_EVENT;
 15787       event.frame_or_window = frame;
 15788       event.arg = key;
 15789       event.modifiers = modifiers;
 15790       event.device = device;
 15791       kbd_buffer_store_event (&event);
 15792       f->last_tool_bar_item = -1;
 15793     }
 15794 }
 15795 
 15796 void
 15797 handle_tool_bar_click (struct frame *f, int x, int y, bool down_p,
 15798                        int modifiers)
 15799 {
 15800   handle_tool_bar_click_with_device (f, x, y, down_p, modifiers, Qt);
 15801 }
 15802 
 15803 /* Possibly highlight a tool-bar item on frame F when mouse moves to
 15804    tool-bar window-relative coordinates X/Y.  Called from
 15805    note_mouse_highlight.  */
 15806 
 15807 static void
 15808 note_tool_bar_highlight (struct frame *f, int x, int y)
 15809 {
 15810   Lisp_Object window = f->tool_bar_window;
 15811   struct window *w = XWINDOW (window);
 15812   Display_Info *dpyinfo = FRAME_DISPLAY_INFO (f);
 15813   Mouse_HLInfo *hlinfo = MOUSE_HL_INFO (f);
 15814   int hpos, vpos;
 15815   struct glyph *glyph;
 15816   struct glyph_row *row;
 15817   int i;
 15818   Lisp_Object enabled_p;
 15819   int prop_idx;
 15820   enum draw_glyphs_face draw = DRAW_IMAGE_RAISED;
 15821   bool mouse_down_p;
 15822   int rc;
 15823 
 15824   /* Function note_mouse_highlight is called with negative X/Y
 15825      values when mouse moves outside of the frame.  */
 15826   if (x <= 0 || y <= 0)
 15827     {
 15828       clear_mouse_face (hlinfo);
 15829       return;
 15830     }
 15831 
 15832   rc = get_tool_bar_item (f, x, y, &glyph, &hpos, &vpos, &prop_idx);
 15833   if (rc < 0)
 15834     {
 15835       /* Not on tool-bar item.  */
 15836       clear_mouse_face (hlinfo);
 15837       return;
 15838     }
 15839   else if (rc == 0)
 15840     /* On same tool-bar item as before.  */
 15841     goto set_help_echo;
 15842 
 15843   clear_mouse_face (hlinfo);
 15844 
 15845   /* Mouse is down, but on different tool-bar item?  */
 15846   mouse_down_p = (gui_mouse_grabbed (dpyinfo)
 15847                   && f == dpyinfo->last_mouse_frame);
 15848 
 15849   if (mouse_down_p && f->last_tool_bar_item != prop_idx)
 15850     return;
 15851 
 15852   draw = mouse_down_p ? DRAW_IMAGE_SUNKEN : DRAW_IMAGE_RAISED;
 15853 
 15854   /* If tool-bar item is not enabled, don't highlight it.  */
 15855   enabled_p = AREF (f->tool_bar_items, prop_idx + TOOL_BAR_ITEM_ENABLED_P);
 15856   if (!NILP (enabled_p) && !NILP (Vmouse_highlight))
 15857     {
 15858       /* Compute the x-position of the glyph.  In front and past the
 15859          image is a space.  We include this in the highlighted area.  */
 15860       row = MATRIX_ROW (w->current_matrix, vpos);
 15861       for (i = x = 0; i < hpos; ++i)
 15862         x += row->glyphs[TEXT_AREA][i].pixel_width;
 15863 
 15864       /* Record this as the current active region.  */
 15865       hlinfo->mouse_face_beg_col = hpos;
 15866       hlinfo->mouse_face_beg_row = vpos;
 15867       hlinfo->mouse_face_beg_x = x;
 15868       hlinfo->mouse_face_past_end = false;
 15869 
 15870       hlinfo->mouse_face_end_col = hpos + 1;
 15871       hlinfo->mouse_face_end_row = vpos;
 15872       hlinfo->mouse_face_end_x = x + glyph->pixel_width;
 15873       hlinfo->mouse_face_window = window;
 15874       hlinfo->mouse_face_face_id = TOOL_BAR_FACE_ID;
 15875 
 15876       /* Display it as active.  */
 15877       show_mouse_face (hlinfo, draw);
 15878     }
 15879 
 15880  set_help_echo:
 15881 
 15882   /* Set help_echo_string to a help string to display for this tool-bar item.
 15883      XTread_socket does the rest.  */
 15884   help_echo_object = help_echo_window = Qnil;
 15885   help_echo_pos = -1;
 15886   help_echo_string = AREF (f->tool_bar_items, prop_idx + TOOL_BAR_ITEM_HELP);
 15887   if (NILP (help_echo_string))
 15888     help_echo_string = AREF (f->tool_bar_items, prop_idx + TOOL_BAR_ITEM_CAPTION);
 15889 }
 15890 
 15891 #endif /* ! (HAVE_EXT_TOOL_BAR) */
 15892 
 15893 #endif /* HAVE_WINDOW_SYSTEM */
 15894 
 15895 
 15896 
 15897 /************************************************************************
 15898                          Horizontal scrolling
 15899  ************************************************************************/
 15900 
 15901 /* For all leaf windows in the window tree rooted at WINDOW, set their
 15902    hscroll value so that PT is (i) visible in the window, and (ii) so
 15903    that it is not within a certain margin at the window's left and
 15904    right border.  Value is true if any window's hscroll has been
 15905    changed.  */
 15906 
 15907 static bool
 15908 hscroll_window_tree (Lisp_Object window)
 15909 {
 15910   bool hscrolled_p = false;
 15911   bool hscroll_relative_p = FLOATP (Vhscroll_step);
 15912   int hscroll_step_abs = 0;
 15913   double hscroll_step_rel = 0;
 15914 
 15915   if (hscroll_relative_p)
 15916     {
 15917       hscroll_step_rel = XFLOAT_DATA (Vhscroll_step);
 15918       if (hscroll_step_rel < 0)
 15919         {
 15920           hscroll_relative_p = false;
 15921           hscroll_step_abs = 0;
 15922         }
 15923     }
 15924   else if (TYPE_RANGED_FIXNUMP (int, Vhscroll_step))
 15925     {
 15926       hscroll_step_abs = XFIXNUM (Vhscroll_step);
 15927       if (hscroll_step_abs < 0)
 15928         hscroll_step_abs = 0;
 15929     }
 15930   else
 15931     hscroll_step_abs = 0;
 15932 
 15933   while (WINDOWP (window))
 15934     {
 15935       struct window *w = XWINDOW (window);
 15936 
 15937       if (WINDOWP (w->contents))
 15938         hscrolled_p |= hscroll_window_tree (w->contents);
 15939       else if (w->cursor.vpos >= 0
 15940                /* Don't allow hscroll in mini-windows that display
 15941                   echo-area messages.  This is because desired_matrix
 15942                   of such windows was prepared while momentarily
 15943                   switched to an echo-area buffer, which is different
 15944                   from w->contents, and we simply cannot hscroll such
 15945                   windows safely.  */
 15946                && !(w == XWINDOW (echo_area_window)
 15947                     && !NILP (echo_area_buffer[0])))
 15948         {
 15949           int h_margin;
 15950           int text_area_width;
 15951           struct glyph_row *cursor_row;
 15952           struct glyph_row *bottom_row;
 15953 
 15954           bottom_row = MATRIX_BOTTOM_TEXT_ROW (w->desired_matrix, w);
 15955           if (w->cursor.vpos < bottom_row - w->desired_matrix->rows)
 15956             cursor_row = MATRIX_ROW (w->desired_matrix, w->cursor.vpos);
 15957           else
 15958             cursor_row = bottom_row - 1;
 15959 
 15960           if (!cursor_row->enabled_p)
 15961             {
 15962               bottom_row = MATRIX_BOTTOM_TEXT_ROW (w->current_matrix, w);
 15963               if (w->cursor.vpos < bottom_row - w->current_matrix->rows)
 15964                 cursor_row = MATRIX_ROW (w->current_matrix, w->cursor.vpos);
 15965               else
 15966                 cursor_row = bottom_row - 1;
 15967             }
 15968           bool row_r2l_p = cursor_row->reversed_p;
 15969           bool hscl = hscrolling_current_line_p (w);
 15970           int x_offset = 0;
 15971           /* When line numbers are displayed, we need to account for
 15972              the horizontal space they consume.  */
 15973           if (!NILP (Vdisplay_line_numbers))
 15974             {
 15975               struct glyph *g;
 15976               if (!row_r2l_p)
 15977                 {
 15978                   for (g = cursor_row->glyphs[TEXT_AREA];
 15979                        g < cursor_row->glyphs[TEXT_AREA]
 15980                          + cursor_row->used[TEXT_AREA];
 15981                        g++)
 15982                     {
 15983                       if (!(NILP (g->object) && g->charpos < 0))
 15984                         break;
 15985                       x_offset += g->pixel_width;
 15986                     }
 15987                 }
 15988               else
 15989                 {
 15990                   for (g = cursor_row->glyphs[TEXT_AREA]
 15991                          + cursor_row->used[TEXT_AREA];
 15992                        g > cursor_row->glyphs[TEXT_AREA];
 15993                        g--)
 15994                     {
 15995                       if (!(NILP ((g - 1)->object) && (g - 1)->charpos < 0))
 15996                         break;
 15997                       x_offset += (g - 1)->pixel_width;
 15998                     }
 15999                 }
 16000             }
 16001           if (cursor_row->truncated_on_left_p)
 16002             {
 16003               /* On TTY frames, don't count the left truncation glyph.  */
 16004               struct frame *f = XFRAME (WINDOW_FRAME (w));
 16005               x_offset -= (FRAME_TERMCAP_P (f) || FRAME_MSDOS_P (f));
 16006             }
 16007 
 16008           text_area_width = window_box_width (w, TEXT_AREA);
 16009 
 16010           /* Scroll when cursor is inside this scroll margin.  */
 16011           h_margin = (clip_to_bounds (0, hscroll_margin, 1000000)
 16012                       * WINDOW_FRAME_COLUMN_WIDTH (w));
 16013 
 16014           /* If the position of this window's point has explicitly
 16015              changed, no more suspend auto hscrolling.  */
 16016           if (w->suspend_auto_hscroll
 16017               && NILP (Fequal (Fwindow_point (window),
 16018                                Fwindow_old_point (window))))
 16019             {
 16020               w->suspend_auto_hscroll = false;
 16021               /* When hscrolling just the current line, and the rest
 16022                  of lines were temporarily hscrolled, but no longer
 16023                  are, force thorough redisplay of this window, to show
 16024                  the effect of disabling hscroll suspension immediately.  */
 16025               if (w->min_hscroll == 0 && w->hscroll > 0
 16026                   && EQ (Fbuffer_local_value (Qauto_hscroll_mode, w->contents),
 16027                          Qcurrent_line))
 16028                 SET_FRAME_GARBAGED (XFRAME (w->frame));
 16029             }
 16030 
 16031           /* Remember window point.  */
 16032           Fset_marker (w->old_pointm,
 16033                        ((w == XWINDOW (selected_window))
 16034                         ? make_fixnum (BUF_PT (XBUFFER (w->contents)))
 16035                         : Fmarker_position (w->pointm)),
 16036                        w->contents);
 16037 
 16038           if (!NILP (Fbuffer_local_value (Qauto_hscroll_mode, w->contents))
 16039               && !w->suspend_auto_hscroll
 16040               /* In some pathological cases, like restoring a window
 16041                  configuration into a frame that is much smaller than
 16042                  the one from which the configuration was saved, we
 16043                  get glyph rows whose start and end have zero buffer
 16044                  positions, which we cannot handle below.  Just skip
 16045                  such windows.  */
 16046               && (CHARPOS (cursor_row->start.pos)
 16047                   >= BUF_BEG (XBUFFER (w->contents)))
 16048               /* For left-to-right rows, hscroll when cursor is either
 16049                  (i) inside the right hscroll margin, or (ii) if it is
 16050                  inside the left margin and the window is already
 16051                  hscrolled.  */
 16052               && ((!row_r2l_p
 16053                    && ((w->hscroll && w->cursor.x <= h_margin + x_offset)
 16054                        || (cursor_row->enabled_p
 16055                            && cursor_row->truncated_on_right_p
 16056                            && (w->cursor.x >= text_area_width - h_margin))))
 16057                   /* For right-to-left rows, the logic is similar,
 16058                      except that rules for scrolling to left and right
 16059                      are reversed.  E.g., if cursor.x <= h_margin, we
 16060                      need to hscroll "to the right" unconditionally,
 16061                      and that will scroll the screen to the left so as
 16062                      to reveal the next portion of the row.  */
 16063                   || (row_r2l_p
 16064                       && ((cursor_row->enabled_p
 16065                            /* FIXME: It is confusing to set the
 16066                               truncated_on_right_p flag when R2L rows
 16067                               are actually truncated on the left.  */
 16068                            && cursor_row->truncated_on_right_p
 16069                            && w->cursor.x <= h_margin)
 16070                           || (w->hscroll
 16071                               && (w->cursor.x >= (text_area_width - h_margin
 16072                                                   - x_offset)))))
 16073                   /* This last condition is needed when moving
 16074                      vertically from an hscrolled line to a short line
 16075                      that doesn't need to be hscrolled.  If we omit
 16076                      this condition, the line from which we move will
 16077                      remain hscrolled.  */
 16078                   || (hscl
 16079                       && w->hscroll != w->min_hscroll
 16080                       && !cursor_row->truncated_on_left_p)))
 16081             {
 16082               struct it it;
 16083               ptrdiff_t hscroll;
 16084               struct buffer *saved_current_buffer;
 16085               ptrdiff_t pt;
 16086               int wanted_x;
 16087 
 16088               /* Find point in a display of infinite width.  */
 16089               saved_current_buffer = current_buffer;
 16090               current_buffer = XBUFFER (w->contents);
 16091 
 16092               if (w == XWINDOW (selected_window))
 16093                 pt = PT;
 16094               else
 16095                 pt = clip_to_bounds (BEGV, marker_position (w->pointm), ZV);
 16096 
 16097               /* Move iterator to pt starting at cursor_row->start in
 16098                  a line with infinite width.  */
 16099               init_to_row_start (&it, w, cursor_row);
 16100               if (hscl)
 16101                 it.first_visible_x = window_hscroll_limited (w, it.f)
 16102                                      * FRAME_COLUMN_WIDTH (it.f);
 16103               it.last_visible_x = DISP_INFINITY;
 16104 
 16105               ptrdiff_t nchars = pt - IT_CHARPOS (it);
 16106               if (current_buffer->long_line_optimizations_p
 16107                   && nchars > large_hscroll_threshold)
 16108                 {
 16109                   /* Special optimization for very long and truncated
 16110                      lines which need to be hscrolled far to the left:
 16111                      jump directly to the (approximate) first position
 16112                      that is visible, instead of slowly walking there.  */
 16113                   fast_move_it_horizontally (&it, nchars);
 16114                   it.current_x += nchars * FRAME_COLUMN_WIDTH (it.f);
 16115                 }
 16116               else
 16117                 move_it_in_display_line_to (&it, pt, -1, MOVE_TO_POS);
 16118               /* If the line ends in an overlay string with a newline,
 16119                  we might infloop, because displaying the window will
 16120                  want to put the cursor after the overlay, i.e. at X
 16121                  coordinate of zero on the next screen line.  So we
 16122                  use the buffer position prior to the overlay string
 16123                  instead.  */
 16124               if (it.method == GET_FROM_STRING && pt > 1)
 16125                 {
 16126                   init_to_row_start (&it, w, cursor_row);
 16127                   if (hscl)
 16128                     it.first_visible_x = (window_hscroll_limited (w, it.f)
 16129                                           * FRAME_COLUMN_WIDTH (it.f));
 16130                   if (current_buffer->long_line_optimizations_p
 16131                       && nchars > large_hscroll_threshold)
 16132                     {
 16133                       fast_move_it_horizontally (&it, nchars - 1);
 16134                       it.current_x += (nchars - 1) * FRAME_COLUMN_WIDTH (it.f);
 16135                     }
 16136                   else
 16137                     move_it_in_display_line_to (&it, pt - 1, -1, MOVE_TO_POS);
 16138                 }
 16139               current_buffer = saved_current_buffer;
 16140 
 16141               /* Position cursor in window.  */
 16142               if (!hscroll_relative_p && hscroll_step_abs == 0)
 16143                 hscroll = max (0, (it.current_x
 16144                                    - (ITERATOR_AT_END_OF_LINE_P (&it)
 16145                                       ? (text_area_width - 4 * FRAME_COLUMN_WIDTH (it.f))
 16146                                       : (text_area_width / 2))))
 16147                           / FRAME_COLUMN_WIDTH (it.f);
 16148               else if ((!row_r2l_p
 16149                         && w->cursor.x >= text_area_width - h_margin)
 16150                        || (row_r2l_p && w->cursor.x <= h_margin))
 16151                 {
 16152                   if (hscroll_relative_p)
 16153                     wanted_x = text_area_width * (1 - hscroll_step_rel)
 16154                                - h_margin;
 16155                   else
 16156                     wanted_x = text_area_width
 16157                                - hscroll_step_abs * FRAME_COLUMN_WIDTH (it.f)
 16158                                - h_margin;
 16159                   hscroll
 16160                     = max (0, it.current_x - wanted_x) / FRAME_COLUMN_WIDTH (it.f);
 16161                 }
 16162               else
 16163                 {
 16164                   if (hscroll_relative_p)
 16165                     wanted_x =
 16166                       text_area_width * hscroll_step_rel + h_margin + x_offset;
 16167                   else
 16168                     wanted_x =
 16169                       hscroll_step_abs * FRAME_COLUMN_WIDTH (it.f)
 16170                       + h_margin + x_offset;
 16171                   hscroll
 16172                     = max (0, it.current_x - wanted_x) / FRAME_COLUMN_WIDTH (it.f);
 16173                 }
 16174               hscroll = max (hscroll, w->min_hscroll);
 16175 
 16176               /* Don't prevent redisplay optimizations if hscroll
 16177                  hasn't changed, as it will unnecessarily slow down
 16178                  redisplay.  */
 16179               if (w->hscroll != hscroll
 16180                   /* When hscrolling only the current line, we need to
 16181                      report hscroll even if its value is equal to the
 16182                      previous one, because the new line might need a
 16183                      different value.  */
 16184                   || (hscl && w->last_cursor_vpos != w->cursor.vpos))
 16185                 {
 16186                   struct buffer *b = XBUFFER (w->contents);
 16187                   b->prevent_redisplay_optimizations_p = true;
 16188                   w->hscroll = hscroll;
 16189                   hscrolled_p = true;
 16190                 }
 16191             }
 16192         }
 16193 
 16194       window = w->next;
 16195     }
 16196 
 16197   /* Value is true if hscroll of any leaf window has been changed.  */
 16198   return hscrolled_p;
 16199 }
 16200 
 16201 
 16202 /* Set hscroll so that cursor is visible and not inside horizontal
 16203    scroll margins for all windows in the tree rooted at WINDOW.  See
 16204    also hscroll_window_tree above.  Value is true if any window's
 16205    hscroll has been changed.  If it has, desired matrices on the frame
 16206    of WINDOW are cleared.  */
 16207 
 16208 static bool
 16209 hscroll_windows (Lisp_Object window)
 16210 {
 16211   bool hscrolled_p = hscroll_window_tree (window);
 16212   if (hscrolled_p)
 16213     clear_desired_matrices (XFRAME (WINDOW_FRAME (XWINDOW (window))));
 16214   return hscrolled_p;
 16215 }
 16216 
 16217 
 16218 
 16219 /************************************************************************
 16220                                 Redisplay
 16221  ************************************************************************/
 16222 
 16223 /* Variables holding some state of redisplay if GLYPH_DEBUG is defined.
 16224    This is sometimes handy to have in a debugger session.  */
 16225 
 16226 #ifdef GLYPH_DEBUG
 16227 
 16228 /* First and last unchanged row for try_window_id.  */
 16229 
 16230 static int debug_first_unchanged_at_end_vpos;
 16231 static int debug_last_unchanged_at_beg_vpos;
 16232 
 16233 /* Delta vpos and y.  */
 16234 
 16235 static int debug_dvpos, debug_dy;
 16236 
 16237 /* Delta in characters and bytes for try_window_id.  */
 16238 
 16239 static ptrdiff_t debug_delta, debug_delta_bytes;
 16240 
 16241 /* Values of window_end_pos and window_end_vpos at the end of
 16242    try_window_id.  */
 16243 
 16244 static ptrdiff_t debug_end_vpos;
 16245 
 16246 /* Append a string to W->desired_matrix->method.  FMT is a printf
 16247    format string.  If trace_redisplay_p is true also printf the
 16248    resulting string to stderr.  */
 16249 
 16250 static void debug_method_add (struct window *, char const *, ...)
 16251   ATTRIBUTE_FORMAT_PRINTF (2, 3);
 16252 
 16253 static void
 16254 debug_method_add (struct window *w, char const *fmt, ...)
 16255 {
 16256   void *ptr = w;
 16257   char *method = w->desired_matrix->method;
 16258   int len = strlen (method);
 16259   int size = sizeof w->desired_matrix->method;
 16260   int remaining = size - len - 1;
 16261   va_list ap;
 16262 
 16263   if (len && remaining)
 16264     {
 16265       method[len] = '|';
 16266       --remaining, ++len;
 16267     }
 16268 
 16269   va_start (ap, fmt);
 16270   vsnprintf (method + len, remaining + 1, fmt, ap);
 16271   va_end (ap);
 16272 
 16273   if (trace_redisplay_p)
 16274     fprintf (stderr, "%p (%s): %s\n",
 16275              ptr,
 16276              ((BUFFERP (w->contents)
 16277                && STRINGP (BVAR (XBUFFER (w->contents), name)))
 16278               ? SSDATA (BVAR (XBUFFER (w->contents), name))
 16279               : "no buffer"),
 16280              method + len);
 16281 }
 16282 
 16283 #endif /* GLYPH_DEBUG */
 16284 
 16285 
 16286 /* Value is true if all changes in window W, which displays
 16287    current_buffer, are in the text between START and END.  START is a
 16288    buffer position, END is given as a distance from Z.  Used in
 16289    redisplay_internal for display optimization.  */
 16290 
 16291 static bool
 16292 text_outside_line_unchanged_p (struct window *w,
 16293                                ptrdiff_t start, ptrdiff_t end)
 16294 {
 16295   bool unchanged_p = true;
 16296 
 16297   /* If text or overlays have changed, see where.  */
 16298   if (window_outdated (w))
 16299     {
 16300       /* Gap in the line?  */
 16301       if (GPT < start || Z - GPT < end)
 16302         unchanged_p = false;
 16303 
 16304       /* Changes start in front of the line, or end after it?  */
 16305       if (unchanged_p
 16306           && (BEG_UNCHANGED < start - 1
 16307               || END_UNCHANGED < end))
 16308         unchanged_p = false;
 16309 
 16310       /* If selective display, can't optimize if changes start at the
 16311          beginning of the line.  */
 16312       if (unchanged_p
 16313           && FIXNUMP (BVAR (current_buffer, selective_display))
 16314           && XFIXNUM (BVAR (current_buffer, selective_display)) > 0
 16315           && (BEG_UNCHANGED < start || GPT <= start))
 16316         unchanged_p = false;
 16317 
 16318       /* If there are overlays at the start or end of the line, these
 16319          may have overlay strings with newlines in them.  A change at
 16320          START, for instance, may actually concern the display of such
 16321          overlay strings as well, and they are displayed on different
 16322          lines.  So, quickly rule out this case.  (For the future, it
 16323          might be desirable to implement something more telling than
 16324          just BEG/END_UNCHANGED.)  */
 16325       if (unchanged_p)
 16326         {
 16327           if (BEG + BEG_UNCHANGED == start
 16328               && overlay_touches_p (start))
 16329             unchanged_p = false;
 16330           if (END_UNCHANGED == end
 16331               && overlay_touches_p (Z - end))
 16332             unchanged_p = false;
 16333         }
 16334 
 16335       /* Under bidi reordering, adding or deleting a character in the
 16336          beginning of a paragraph, before the first strong directional
 16337          character, can change the base direction of the paragraph (unless
 16338          the buffer specifies a fixed paragraph direction), which will
 16339          require redisplaying the whole paragraph.  It might be worthwhile
 16340          to find the paragraph limits and widen the range of redisplayed
 16341          lines to that, but for now just give up this optimization.  */
 16342       if (!NILP (BVAR (XBUFFER (w->contents), bidi_display_reordering))
 16343           && NILP (BVAR (XBUFFER (w->contents), bidi_paragraph_direction)))
 16344         unchanged_p = false;
 16345     }
 16346 
 16347   return unchanged_p;
 16348 }
 16349 
 16350 
 16351 /* Do a frame update, taking possible shortcuts into account.  This is
 16352    the main external entry point for redisplay.
 16353 
 16354    If the last redisplay displayed an echo area message and that message
 16355    is no longer requested, we clear the echo area or bring back the
 16356    mini-buffer if that is in use.  */
 16357 
 16358 void
 16359 redisplay (void)
 16360 {
 16361   redisplay_internal ();
 16362 }
 16363 
 16364 
 16365 static Lisp_Object
 16366 overlay_arrow_string_or_property (Lisp_Object var)
 16367 {
 16368   Lisp_Object val;
 16369 
 16370   if (val = Fget (var, Qoverlay_arrow_string), STRINGP (val))
 16371     return val;
 16372 
 16373   return Voverlay_arrow_string;
 16374 }
 16375 
 16376 /* Return true if there are any overlay-arrows in current_buffer.  */
 16377 static bool
 16378 overlay_arrow_in_current_buffer_p (void)
 16379 {
 16380   Lisp_Object vlist;
 16381 
 16382   for (vlist = Voverlay_arrow_variable_list;
 16383        CONSP (vlist);
 16384        vlist = XCDR (vlist))
 16385     {
 16386       Lisp_Object var = XCAR (vlist);
 16387       Lisp_Object val;
 16388 
 16389       if (!SYMBOLP (var))
 16390         continue;
 16391       val = find_symbol_value (var);
 16392       if (MARKERP (val)
 16393           && current_buffer == XMARKER (val)->buffer)
 16394         return true;
 16395     }
 16396   return false;
 16397 }
 16398 
 16399 
 16400 /* Return true if any overlay_arrows have moved or overlay-arrow-string
 16401    has changed.
 16402    If SET_REDISPLAY is true, additionally, set the `redisplay' bit in those
 16403    buffers that are affected.  */
 16404 
 16405 static bool
 16406 overlay_arrows_changed_p (bool set_redisplay)
 16407 {
 16408   Lisp_Object vlist;
 16409   bool changed = false;
 16410 
 16411   for (vlist = Voverlay_arrow_variable_list;
 16412        CONSP (vlist);
 16413        vlist = XCDR (vlist))
 16414     {
 16415       Lisp_Object var = XCAR (vlist);
 16416       Lisp_Object val, pstr;
 16417 
 16418       if (!SYMBOLP (var))
 16419         continue;
 16420       val = find_symbol_value (var);
 16421       if (!MARKERP (val))
 16422         continue;
 16423       if (! EQ (Fmarker_position (val),
 16424                 /* FIXME: Don't we have a problem, using such a global
 16425                  * "last-position" if the variable is buffer-local?  */
 16426                 Fget (var, Qlast_arrow_position))
 16427           || ! (pstr = overlay_arrow_string_or_property (var),
 16428                 EQ (pstr, Fget (var, Qlast_arrow_string))))
 16429         {
 16430           struct buffer *buf = XMARKER (val)->buffer;
 16431 
 16432           if (set_redisplay)
 16433             {
 16434               if (buf)
 16435                 bset_redisplay (buf);
 16436               changed = true;
 16437             }
 16438           else
 16439             return true;
 16440         }
 16441     }
 16442   return changed;
 16443 }
 16444 
 16445 /* Mark overlay arrows to be updated on next redisplay.  */
 16446 
 16447 static void
 16448 update_overlay_arrows (int up_to_date)
 16449 {
 16450   Lisp_Object vlist;
 16451 
 16452   for (vlist = Voverlay_arrow_variable_list;
 16453        CONSP (vlist);
 16454        vlist = XCDR (vlist))
 16455     {
 16456       Lisp_Object var = XCAR (vlist);
 16457 
 16458       if (!SYMBOLP (var))
 16459         continue;
 16460 
 16461       if (up_to_date > 0)
 16462         {
 16463           Lisp_Object val = find_symbol_value (var);
 16464           if (!MARKERP (val))
 16465             continue;
 16466           Fput (var, Qlast_arrow_position, Fmarker_position (val));
 16467           Fput (var, Qlast_arrow_string,
 16468                 overlay_arrow_string_or_property (var));
 16469         }
 16470       else if (up_to_date < 0
 16471                || !NILP (Fget (var, Qlast_arrow_position)))
 16472         {
 16473           Fput (var, Qlast_arrow_position, Qt);
 16474           Fput (var, Qlast_arrow_string, Qt);
 16475         }
 16476     }
 16477 }
 16478 
 16479 
 16480 /* Return overlay arrow string to display at row.
 16481    Return integer (bitmap number) for arrow bitmap in left fringe.
 16482    Return nil if no overlay arrow.  */
 16483 
 16484 static Lisp_Object
 16485 overlay_arrow_at_row (struct it *it, struct glyph_row *row)
 16486 {
 16487   Lisp_Object vlist;
 16488 
 16489   for (vlist = Voverlay_arrow_variable_list;
 16490        CONSP (vlist);
 16491        vlist = XCDR (vlist))
 16492     {
 16493       Lisp_Object var = XCAR (vlist);
 16494       Lisp_Object val;
 16495 
 16496       if (!SYMBOLP (var))
 16497         continue;
 16498 
 16499       val = find_symbol_value (var);
 16500 
 16501       if (MARKERP (val)
 16502           && current_buffer == XMARKER (val)->buffer
 16503           && (MATRIX_ROW_START_CHARPOS (row) == marker_position (val)))
 16504         {
 16505           if (FRAME_WINDOW_P (it->f)
 16506               /* FIXME: if ROW->reversed_p is set, this should test
 16507                  the right fringe, not the left one.  */
 16508               && WINDOW_LEFT_FRINGE_WIDTH (it->w) > 0)
 16509             {
 16510 #ifdef HAVE_WINDOW_SYSTEM
 16511               if (val = Fget (var, Qoverlay_arrow_bitmap), SYMBOLP (val))
 16512                 {
 16513                   int fringe_bitmap = lookup_fringe_bitmap (val);
 16514                   if (fringe_bitmap != 0)
 16515                     return make_fixnum (fringe_bitmap);
 16516                 }
 16517 #endif
 16518               return make_fixnum (-1); /* Use default arrow bitmap.  */
 16519             }
 16520           return overlay_arrow_string_or_property (var);
 16521         }
 16522     }
 16523 
 16524   return Qnil;
 16525 }
 16526 
 16527 /* Return true if point moved out of or into a composition.  Otherwise
 16528    return false.  PREV_BUF and PREV_PT are the last point buffer and
 16529    position.  BUF and PT are the current point buffer and position.  */
 16530 
 16531 static bool
 16532 check_point_in_composition (struct buffer *prev_buf, ptrdiff_t prev_pt,
 16533                             struct buffer *buf, ptrdiff_t pt)
 16534 {
 16535   ptrdiff_t start, end;
 16536   Lisp_Object prop;
 16537   Lisp_Object buffer;
 16538 
 16539   XSETBUFFER (buffer, buf);
 16540   /* Check a composition at the last point if point moved within the
 16541      same buffer.  */
 16542   if (prev_buf == buf)
 16543     {
 16544       if (prev_pt == pt)
 16545         /* Point didn't move.  */
 16546         return false;
 16547 
 16548       if (prev_pt > BUF_BEGV (buf) && prev_pt < BUF_ZV (buf)
 16549           && find_composition (prev_pt, -1, &start, &end, &prop, buffer)
 16550           && composition_valid_p (start, end, prop)
 16551           && start < prev_pt && end > prev_pt)
 16552         /* The last point was within the composition.  Return true iff
 16553             point moved out of the composition.  */
 16554         return (pt <= start || pt >= end);
 16555     }
 16556 
 16557   /* Check a composition at the current point.  */
 16558   return (pt > BUF_BEGV (buf) && pt < BUF_ZV (buf)
 16559           && find_composition (pt, -1, &start, &end, &prop, buffer)
 16560           && composition_valid_p (start, end, prop)
 16561           && start < pt && end > pt);
 16562 }
 16563 
 16564 /* Reconsider the clip changes of buffer which is displayed in W.  */
 16565 
 16566 static void
 16567 reconsider_clip_changes (struct window *w)
 16568 {
 16569   struct buffer *b = XBUFFER (w->contents);
 16570 
 16571   if (b->clip_changed
 16572       && w->window_end_valid
 16573       && w->current_matrix->buffer == b
 16574       && w->current_matrix->zv == BUF_ZV (b)
 16575       && w->current_matrix->begv == BUF_BEGV (b))
 16576     b->clip_changed = false;
 16577 
 16578   /* If display wasn't paused, and W is not a tool bar window, see if
 16579      point has been moved into or out of a composition.  In that case,
 16580      set b->clip_changed to force updating the screen.  If
 16581      b->clip_changed has already been set, skip this check.  */
 16582   if (!b->clip_changed && w->window_end_valid)
 16583     {
 16584       ptrdiff_t pt = (w == XWINDOW (selected_window)
 16585                       ? PT : marker_position (w->pointm));
 16586 
 16587       if ((w->current_matrix->buffer != b || pt != w->last_point)
 16588           && check_point_in_composition (w->current_matrix->buffer,
 16589                                          w->last_point, b, pt))
 16590         b->clip_changed = true;
 16591     }
 16592 }
 16593 
 16594 static void
 16595 propagate_buffer_redisplay (void)
 16596 { /* Resetting b->text->redisplay is problematic!
 16597      We can't just reset it in the case that some window that displays
 16598      it has not been redisplayed; and such a window can stay
 16599      unredisplayed for a long time if it's currently invisible.
 16600      But we do want to reset it at the end of redisplay otherwise
 16601      its displayed windows will keep being redisplayed over and over
 16602      again.
 16603      So we copy all b->text->redisplay flags up to their windows here,
 16604      such that mark_window_display_accurate can safely reset
 16605      b->text->redisplay.  */
 16606   Lisp_Object ws = window_list ();
 16607   for (; CONSP (ws); ws = XCDR (ws))
 16608     {
 16609       struct window *thisw = XWINDOW (XCAR (ws));
 16610       struct buffer *thisb = XBUFFER (thisw->contents);
 16611       if (thisb->text->redisplay)
 16612         thisw->redisplay = true;
 16613     }
 16614 }
 16615 
 16616 #define STOP_POLLING                                    \
 16617 do { if (! polling_stopped_here) stop_polling ();       \
 16618        polling_stopped_here = true; } while (false)
 16619 
 16620 #define RESUME_POLLING                                  \
 16621 do { if (polling_stopped_here) start_polling ();        \
 16622        polling_stopped_here = false; } while (false)
 16623 
 16624 /* Perhaps in the future avoid recentering windows if it
 16625    is not necessary; currently that causes some problems.  */
 16626 
 16627 static void
 16628 redisplay_internal (void)
 16629 {
 16630   struct window *w = XWINDOW (selected_window);
 16631   struct window *sw;
 16632   struct frame *fr;
 16633   bool pending;
 16634   bool must_finish = false, match_p;
 16635   struct text_pos tlbufpos, tlendpos;
 16636   int number_of_visible_frames;
 16637   struct frame *sf;
 16638   bool polling_stopped_here = false;
 16639   Lisp_Object tail, frame;
 16640 
 16641   /* Set a limit to the number of retries we perform due to horizontal
 16642      scrolling, this avoids getting stuck in an uninterruptible
 16643      infinite loop (Bug #24633).  */
 16644   enum { MAX_HSCROLL_RETRIES = 16 };
 16645   int hscroll_retries = 0;
 16646 
 16647   /* Limit the number of retries for when frame(s) become garbaged as
 16648      result of redisplaying them.  Some packages set various redisplay
 16649      hooks, such as window-scroll-functions, to run Lisp that always
 16650      calls APIs which cause the frame's garbaged flag to become set,
 16651      so we loop indefinitely.  */
 16652   enum {MAX_GARBAGED_FRAME_RETRIES = 2 };
 16653   int garbaged_frame_retries = 0;
 16654 
 16655   /* False means that only the selected_window needs to be updated.
 16656      True means that other windows may need to be updated as well,
 16657      so we need to consult `needs_no_update` for all windows.  */
 16658   bool consider_all_windows_p;
 16659 
 16660   /* True means redisplay has to redisplay the miniwindow.  */
 16661   bool update_miniwindow_p = false;
 16662 
 16663   redisplay_trace ("redisplay_internal %d\n", redisplaying_p);
 16664 
 16665   /* No redisplay if running in batch mode or frame is not yet fully
 16666      initialized, or redisplay is explicitly turned off by setting
 16667      Vinhibit_redisplay.  */
 16668   if ((FRAME_INITIAL_P (SELECTED_FRAME ())
 16669        && redisplay_skip_initial_frame)
 16670       || !NILP (Vinhibit_redisplay))
 16671     return;
 16672 
 16673   /* Don't examine these until after testing Vinhibit_redisplay.
 16674      When Emacs is shutting down, perhaps because its connection to
 16675      X has dropped, we should not look at them at all.  */
 16676   fr = XFRAME (w->frame);
 16677   sf = SELECTED_FRAME ();
 16678 
 16679   if (!fr->glyphs_initialized_p)
 16680     return;
 16681 
 16682 #if defined (USE_X_TOOLKIT) || defined (USE_GTK) || defined (HAVE_NS)
 16683   if (popup_activated ())
 16684     return;
 16685 #endif
 16686 
 16687 #if defined (HAVE_HAIKU)
 16688   if (popup_activated_p)
 16689     return;
 16690 #endif
 16691 
 16692   /* I don't think this happens but let's be paranoid.  */
 16693   if (redisplaying_p)
 16694     return;
 16695 
 16696   /* Record a function that clears redisplaying_p
 16697      when we leave this function.  */
 16698   specpdl_ref count = SPECPDL_INDEX ();
 16699   record_unwind_protect_void (unwind_redisplay);
 16700   redisplaying_p = true;
 16701   block_buffer_flips ();
 16702   specbind (Qinhibit_free_realized_faces, Qnil);
 16703 
 16704   /* Record this function, so it appears on the profiler's backtraces.  */
 16705   record_in_backtrace (Qredisplay_internal_xC_functionx, 0, 0);
 16706 
 16707   FOR_EACH_FRAME (tail, frame)
 16708     XFRAME (frame)->already_hscrolled_p = false;
 16709 
 16710   reset_outermost_restrictions ();
 16711 
 16712  retry:
 16713   /* Remember the currently selected window.  */
 16714   sw = w;
 16715 
 16716   pending = false;
 16717   forget_escape_and_glyphless_faces ();
 16718 
 16719   inhibit_free_realized_faces = false;
 16720 
 16721   /* If face_change, init_iterator will free all realized faces, which
 16722      includes the faces referenced from current matrices.  So, we
 16723      can't reuse current matrices in this case.  */
 16724   if (face_change)
 16725     windows_or_buffers_changed = 47;
 16726 
 16727   if ((FRAME_TERMCAP_P (sf) || FRAME_MSDOS_P (sf))
 16728       && FRAME_TTY (sf)->previous_frame != sf)
 16729     {
 16730       /* Since frames on a single ASCII terminal share the same
 16731          display area, displaying a different frame means redisplay
 16732          the whole thing.  */
 16733       SET_FRAME_GARBAGED (sf);
 16734 #if !defined DOS_NT && !defined HAVE_ANDROID
 16735       set_tty_color_mode (FRAME_TTY (sf), sf);
 16736 #endif
 16737       FRAME_TTY (sf)->previous_frame = sf;
 16738     }
 16739 
 16740   /* Set the visible flags for all frames.  Do this before checking for
 16741      resized or garbaged frames; they want to know if their frames are
 16742      visible.  See the comment in frame.h for FRAME_SAMPLE_VISIBILITY.  */
 16743   number_of_visible_frames = 0;
 16744 
 16745   FOR_EACH_FRAME (tail, frame)
 16746     {
 16747       struct frame *f = XFRAME (frame);
 16748 
 16749       if (FRAME_REDISPLAY_P (f))
 16750         {
 16751           ++number_of_visible_frames;
 16752           /* Adjust matrices for visible frames only.  */
 16753           if (f->fonts_changed)
 16754             {
 16755               adjust_frame_glyphs (f);
 16756               /* Disable all redisplay optimizations for this frame.
 16757                  This is because adjust_frame_glyphs resets the
 16758                  enabled_p flag for all glyph rows of all windows, so
 16759                  many optimizations will fail anyway, and some might
 16760                  fail to test that flag and do bogus things as
 16761                  result.  */
 16762               SET_FRAME_GARBAGED (f);
 16763               f->fonts_changed = false;
 16764             }
 16765           /* If cursor type has been changed on the frame
 16766              other than selected, consider all frames.  */
 16767           if (f != sf && f->cursor_type_changed)
 16768             fset_redisplay (f);
 16769         }
 16770       clear_desired_matrices (f);
 16771     }
 16772 
 16773   /* Notice any pending interrupt request to change frame size.  */
 16774   do_pending_window_change (true);
 16775 
 16776   /* Clear frames marked as garbaged.  */
 16777   clear_garbaged_frames ();
 16778 
 16779   /* Build menubar and tool-bar items.  */
 16780   if (NILP (Vmemory_full))
 16781     prepare_menu_bars ();
 16782 
 16783   /* do_pending_window_change could change the selected_window due to
 16784      frame resizing which makes the selected window too small.
 16785      prepare_menu_bars may call lisp hooks and hence also change the
 16786      selected_window.  */
 16787   if (WINDOWP (selected_window) && (w = XWINDOW (selected_window)) != sw)
 16788     sw = w;
 16789 
 16790   reconsider_clip_changes (w);
 16791 
 16792   /* In most cases selected window displays current buffer.  */
 16793   match_p = XBUFFER (w->contents) == current_buffer;
 16794   if (match_p)
 16795     {
 16796       /* Detect case that we need to write or remove a star in the mode line.  */
 16797       if ((SAVE_MODIFF < MODIFF) != w->last_had_star)
 16798         w->update_mode_line = true;
 16799 
 16800       if (mode_line_update_needed (w))
 16801         w->update_mode_line = true;
 16802 
 16803       /* If reconsider_clip_changes above decided that the narrowing
 16804          in the current buffer changed, make sure all other windows
 16805          showing that buffer will be redisplayed.  */
 16806       if (current_buffer->clip_changed)
 16807         bset_update_mode_line (current_buffer);
 16808     }
 16809 
 16810   /* Normally the message* functions will have already displayed and
 16811      updated the echo area, but the frame may have been trashed, or
 16812      the update may have been preempted, so display the echo area
 16813      again here.  Checking message_cleared_p captures the case that
 16814      the echo area should be cleared.  */
 16815   if ((!NILP (echo_area_buffer[0]) && !display_last_displayed_message_p)
 16816       || (!NILP (echo_area_buffer[1]) && display_last_displayed_message_p)
 16817       || (message_cleared_p
 16818           && minibuf_level == 0
 16819           /* If the mini-window is currently selected, this means the
 16820              echo-area doesn't show through.  */
 16821           && !MINI_WINDOW_P (XWINDOW (selected_window))))
 16822     {
 16823       echo_area_display (false);
 16824 
 16825       if (message_cleared_p)
 16826         update_miniwindow_p = true;
 16827 
 16828       must_finish = true;
 16829 
 16830       /* If we don't display the current message, don't clear the
 16831          message_cleared_p flag, because, if we did, we wouldn't clear
 16832          the echo area in the next redisplay which doesn't preserve
 16833          the echo area.  */
 16834       if (!display_last_displayed_message_p)
 16835         message_cleared_p = false;
 16836     }
 16837   else if (EQ (selected_window, minibuf_window)
 16838            && (current_buffer->clip_changed || window_outdated (w))
 16839            && resize_mini_window (w, false))
 16840     {
 16841       /* Resized active mini-window to fit the size of what it is
 16842          showing if its contents might have changed.  */
 16843       must_finish = true;
 16844 
 16845       /* If window configuration was changed, frames may have been
 16846          marked garbaged.  Clear them or we will experience
 16847          surprises wrt scrolling.  */
 16848       clear_garbaged_frames ();
 16849     }
 16850 
 16851   if (!NILP (Vrun_hooks))
 16852     run_window_change_functions ();
 16853 
 16854   if (windows_or_buffers_changed && !update_mode_lines)
 16855     /* Code that sets windows_or_buffers_changed doesn't distinguish whether
 16856        only the windows's contents needs to be refreshed, or whether the
 16857        mode-lines also need a refresh.  */
 16858     update_mode_lines = (windows_or_buffers_changed == REDISPLAY_SOME
 16859                          ? REDISPLAY_SOME : 32);
 16860 
 16861   /* If specs for an arrow have changed, do thorough redisplay
 16862      to ensure we remove any arrow that should no longer exist.  */
 16863   /* Apparently, this is the only case where we update other windows,
 16864      without updating other mode-lines.  */
 16865   overlay_arrows_changed_p (true);
 16866 
 16867   consider_all_windows_p = (update_mode_lines
 16868                             || windows_or_buffers_changed);
 16869 
 16870 #define AINC(a,i)                                                       \
 16871   {                                                                     \
 16872     Lisp_Object entry = Fgethash (make_fixnum (i), a, make_fixnum (0)); \
 16873     if (FIXNUMP (entry))                                                \
 16874       Fputhash (make_fixnum (i), make_fixnum (1 + XFIXNUM (entry)), a); \
 16875   }
 16876 
 16877   AINC (Vredisplay__all_windows_cause, windows_or_buffers_changed);
 16878   AINC (Vredisplay__mode_lines_cause, update_mode_lines);
 16879 
 16880   /* Optimize the case that only the line containing the cursor in the
 16881      selected window has changed.  Variables starting with this_ are
 16882      set in display_line and record information about the line
 16883      containing the cursor.  */
 16884   tlbufpos = this_line_start_pos;
 16885   tlendpos = this_line_end_pos;
 16886   if (!consider_all_windows_p
 16887       && CHARPOS (tlbufpos) > 0
 16888       && !w->update_mode_line
 16889       && !current_buffer->clip_changed
 16890       && !current_buffer->prevent_redisplay_optimizations_p
 16891       && FRAME_REDISPLAY_P (XFRAME (w->frame))
 16892       && !FRAME_OBSCURED_P (XFRAME (w->frame))
 16893       && !XFRAME (w->frame)->cursor_type_changed
 16894       && !XFRAME (w->frame)->face_change
 16895       /* Make sure recorded data applies to current buffer, etc.  */
 16896       && this_line_buffer == current_buffer
 16897       && match_p
 16898       && !w->force_start
 16899       && !w->optional_new_start
 16900       /* Point must be on the line that we have info recorded about.  */
 16901       && PT >= CHARPOS (tlbufpos)
 16902       && PT <= Z - CHARPOS (tlendpos)
 16903       /* FIXME: The following condition is only needed when
 16904          significant parts of the buffer are hidden (e.g., under
 16905          hs-minor-mode), but there doesn't seem to be a simple way of
 16906          detecting that, so we always disable the one-line redisplay
 16907          optimizations whenever display-line-numbers-mode is turned on
 16908          in the buffer.  */
 16909       && (NILP (Vdisplay_line_numbers)
 16910           || EQ (Vdisplay_line_numbers, Qvisual))
 16911       /* All text outside that line, including its final newline,
 16912          must be unchanged.  */
 16913       && text_outside_line_unchanged_p (w, CHARPOS (tlbufpos),
 16914                                         CHARPOS (tlendpos)))
 16915     {
 16916       if (CHARPOS (tlbufpos) > BEGV
 16917           && FETCH_BYTE (BYTEPOS (tlbufpos) - 1) != '\n'
 16918           && (CHARPOS (tlbufpos) == ZV
 16919               || FETCH_BYTE (BYTEPOS (tlbufpos)) == '\n'))
 16920         /* Former continuation line has disappeared by becoming empty.  */
 16921         goto cancel;
 16922       else if (window_outdated (w) || MINI_WINDOW_P (w))
 16923         {
 16924           /* We have to handle the case of continuation around a
 16925              wide-column character (see the comment in indent.c around
 16926              line 1340).
 16927 
 16928              For instance, in the following case:
 16929 
 16930              --------  Insert  --------
 16931              K_A_N_\\   `a'    K_A_N_a\         `X_' are wide-column chars.
 16932              J_I_       ==>    J_I_             `^^' are cursors.
 16933              ^^                ^^
 16934              --------          --------
 16935 
 16936              As we have to redraw the line above, we cannot use this
 16937              optimization.  */
 16938 
 16939           struct it it;
 16940           int line_height_before = this_line_pixel_height;
 16941 
 16942           /* Note that start_display will handle the case that the
 16943              line starting at tlbufpos is a continuation line.  */
 16944           start_display (&it, w, tlbufpos);
 16945 
 16946           /* Implementation note: It this still necessary?  */
 16947           if (it.current_x != this_line_start_x)
 16948             goto cancel;
 16949 
 16950           /* Give up on this optimization if the line starts with a
 16951              string with display property that draws on the fringes,
 16952              as that might interfere with line-prefix display.  */
 16953           if (it.sp > 1
 16954               && it.method == GET_FROM_IMAGE && it.image_id == -1)
 16955             goto cancel;
 16956           redisplay_trace ("trying display optimization 1\n");
 16957           w->cursor.vpos = -1;
 16958           overlay_arrow_seen = false;
 16959           it.vpos = this_line_vpos;
 16960           it.current_y = this_line_y;
 16961           it.glyph_row = MATRIX_ROW (w->desired_matrix, this_line_vpos);
 16962           display_line (&it, -1);
 16963 
 16964           /* If line contains point, is not continued,
 16965              and ends at same distance from eob as before, we win.  */
 16966           if (w->cursor.vpos >= 0
 16967               /* Line is not continued, otherwise this_line_start_pos
 16968                  would have been set to 0 in display_line.  */
 16969               && CHARPOS (this_line_start_pos)
 16970               /* Line ends as before.  */
 16971               && CHARPOS (this_line_end_pos) == CHARPOS (tlendpos)
 16972               /* Line has same height as before.  Otherwise other lines
 16973                  would have to be shifted up or down.  */
 16974               && this_line_pixel_height == line_height_before
 16975               /* Cannot use this optimization if hscrolling current
 16976                  line and this line is the current one, because
 16977                  display_line above is not informed about the
 16978                  current-line's vpos, and cannot DTRT in that case.  */
 16979               && !hscrolling_current_line_p (w))
 16980             {
 16981               /* If this is not the window's last line, we must adjust
 16982                  the charstarts of the lines below.  */
 16983               if (it.current_y < it.last_visible_y)
 16984                 {
 16985                   struct glyph_row *row
 16986                     = MATRIX_ROW (w->current_matrix, this_line_vpos + 1);
 16987                   ptrdiff_t delta, delta_bytes;
 16988 
 16989                   /* We used to distinguish between two cases here,
 16990                      conditioned by Z - CHARPOS (tlendpos) == ZV, for
 16991                      when the line ends in a newline or the end of the
 16992                      buffer's accessible portion.  But both cases did
 16993                      the same, so they were collapsed.  */
 16994                   delta = (Z
 16995                            - CHARPOS (tlendpos)
 16996                            - MATRIX_ROW_START_CHARPOS (row));
 16997                   delta_bytes = (Z_BYTE
 16998                                  - BYTEPOS (tlendpos)
 16999                                  - MATRIX_ROW_START_BYTEPOS (row));
 17000 
 17001                   increment_matrix_positions (w->current_matrix,
 17002                                               this_line_vpos + 1,
 17003                                               w->current_matrix->nrows,
 17004                                               delta, delta_bytes);
 17005                 }
 17006 
 17007               /* If this row displays text now but previously didn't,
 17008                  or vice versa, w->window_end_vpos may have to be
 17009                  adjusted.  */
 17010               if (MATRIX_ROW_DISPLAYS_TEXT_P (it.glyph_row - 1))
 17011                 {
 17012                   if (w->window_end_vpos < this_line_vpos)
 17013                     w->window_end_vpos = this_line_vpos;
 17014                 }
 17015               else if (w->window_end_vpos == this_line_vpos
 17016                        && this_line_vpos > 0)
 17017                 w->window_end_vpos = this_line_vpos - 1;
 17018               w->window_end_valid = false;
 17019 
 17020               /* Update hint: No need to try to scroll in update_window.  */
 17021               w->desired_matrix->no_scrolling_p = true;
 17022 
 17023 #ifdef GLYPH_DEBUG
 17024               *w->desired_matrix->method = 0;
 17025               debug_method_add (w, "optimization 1");
 17026 #endif
 17027 #ifdef HAVE_WINDOW_SYSTEM
 17028               update_window_fringes (w, false);
 17029 #endif
 17030               goto update;
 17031             }
 17032           else
 17033             goto cancel;
 17034         }
 17035       else if (/* Cursor position hasn't changed.  */
 17036                PT == w->last_point
 17037                /* Make sure the cursor was last displayed
 17038                   in this window.  Otherwise we have to reposition it.  */
 17039 
 17040                /* PXW: Must be converted to pixels, probably.  */
 17041                && 0 <= w->cursor.vpos
 17042                && w->cursor.vpos < WINDOW_TOTAL_LINES (w))
 17043         {
 17044           if (!must_finish)
 17045             {
 17046               do_pending_window_change (true);
 17047               /* If selected_window changed, redisplay again.  */
 17048               if (WINDOWP (selected_window)
 17049                   && (w = XWINDOW (selected_window)) != sw)
 17050                 goto retry;
 17051 
 17052                 /* We used to always goto end_of_redisplay here, but this
 17053                  isn't enough if we have a blinking cursor.  */
 17054               if (w->cursor_off_p == w->last_cursor_off_p)
 17055                 goto end_of_redisplay;
 17056             }
 17057           goto update;
 17058         }
 17059       /* If highlighting the region, or if the cursor is in the echo area,
 17060          then we can't just move the cursor.  */
 17061       else if (NILP (Vshow_trailing_whitespace)
 17062                && !cursor_in_echo_area
 17063                && !composition_break_at_point)
 17064         {
 17065           struct it it;
 17066           struct glyph_row *row;
 17067 
 17068           /* Skip from tlbufpos to PT and see where it is.  Note that
 17069              PT may be in invisible text.  If so, we will end at the
 17070              next visible position.  */
 17071           init_iterator (&it, w, CHARPOS (tlbufpos), BYTEPOS (tlbufpos),
 17072                          NULL, DEFAULT_FACE_ID);
 17073           it.current_x = this_line_start_x;
 17074           it.current_y = this_line_y;
 17075           it.vpos = this_line_vpos;
 17076 
 17077           if (current_buffer->long_line_optimizations_p
 17078               && it.line_wrap == TRUNCATE
 17079               && PT - CHARPOS (tlbufpos) > large_hscroll_threshold)
 17080             {
 17081               /* When lines are very long and truncated, jumping to
 17082                  the next visible line is much faster than slowly
 17083                  iterating there.  */
 17084               reseat_at_next_visible_line_start (&it, false);
 17085               if (IT_CHARPOS (it) <= PT) /* point moved off this line */
 17086                 it.vpos = this_line_vpos + 1;
 17087             }
 17088           else
 17089             {
 17090               /* The call to move_it_to stops in front of PT, but
 17091                  moves over before-strings.  */
 17092               move_it_to (&it, PT, -1, -1, -1, MOVE_TO_POS);
 17093             }
 17094 
 17095           if (it.vpos == this_line_vpos
 17096               && (row = MATRIX_ROW (w->current_matrix, this_line_vpos),
 17097                   row->enabled_p))
 17098             {
 17099               eassert (this_line_vpos == it.vpos);
 17100               eassert (this_line_y == it.current_y);
 17101               set_cursor_from_row (w, row, w->current_matrix, 0, 0, 0, 0);
 17102               if (cursor_row_fully_visible_p (w, false, true, false))
 17103                 {
 17104 #ifdef GLYPH_DEBUG
 17105                   *w->desired_matrix->method = 0;
 17106                   debug_method_add (w, "optimization 3");
 17107 #endif
 17108                   goto update;
 17109                 }
 17110               else
 17111                 goto cancel;
 17112             }
 17113           else
 17114             goto cancel;
 17115         }
 17116 
 17117     cancel:
 17118       /* Text changed drastically or point moved off of line.  */
 17119       SET_MATRIX_ROW_ENABLED_P (w->desired_matrix, this_line_vpos, false);
 17120     }
 17121 
 17122   CHARPOS (this_line_start_pos) = 0;
 17123   ++clear_face_cache_count;
 17124 #ifdef HAVE_WINDOW_SYSTEM
 17125   ++clear_image_cache_count;
 17126 #endif
 17127 
 17128   /* Build desired matrices, and update the display.  If
 17129      consider_all_windows_p, do it for all windows on all frames that
 17130      require redisplay, as specified by their 'redisplay' flag.
 17131      Otherwise do it for selected_window, only.  */
 17132 
 17133   if (consider_all_windows_p)
 17134     {
 17135       FOR_EACH_FRAME (tail, frame)
 17136         XFRAME (frame)->updated_p = false;
 17137 
 17138       propagate_buffer_redisplay ();
 17139 
 17140       FOR_EACH_FRAME (tail, frame)
 17141         {
 17142           struct frame *f = XFRAME (frame);
 17143 
 17144           /* We don't have to do anything for unselected terminal
 17145              frames.  */
 17146           if ((FRAME_TERMCAP_P (f) || FRAME_MSDOS_P (f))
 17147               && !EQ (FRAME_TTY (f)->top_frame, frame))
 17148             continue;
 17149 
 17150         retry_frame:
 17151           if (FRAME_WINDOW_P (f) || FRAME_TERMCAP_P (f) || f == sf)
 17152             {
 17153               bool gcscrollbars
 17154                 /* Only GC scrollbars when we redisplay the whole frame.  */
 17155                 = f->redisplay || !REDISPLAY_SOME_P ();
 17156               bool f_redisplay_flag = f->redisplay;
 17157 
 17158               /* The X error handler may have deleted that frame
 17159                  before we went back to retry_frame.  This must come
 17160                  before any accesses to f->terminal.  */
 17161               if (!FRAME_LIVE_P (f))
 17162                 continue;
 17163 
 17164               /* Mark all the scroll bars to be removed; we'll redeem
 17165                  the ones we want when we redisplay their windows.  */
 17166               if (gcscrollbars && FRAME_TERMINAL (f)->condemn_scroll_bars_hook)
 17167                 FRAME_TERMINAL (f)->condemn_scroll_bars_hook (f);
 17168 
 17169               if (FRAME_REDISPLAY_P (f) && !FRAME_OBSCURED_P (f))
 17170                 {
 17171                   /* Don't allow freeing images and faces for this
 17172                      frame as long as the frame's update wasn't
 17173                      completed.  This prevents crashes when some Lisp
 17174                      that runs from the various hooks or font-lock
 17175                      decides to clear the frame's image cache and face
 17176                      cache, when the images and faces in those caches
 17177                      are referenced by the desired matrix.  */
 17178                   f->inhibit_clear_image_cache = true;
 17179                   redisplay_windows (FRAME_ROOT_WINDOW (f));
 17180                 }
 17181               /* Remember that the invisible frames need to be redisplayed next
 17182                  time they're visible.  */
 17183               else if (!REDISPLAY_SOME_P ())
 17184                 f->redisplay = true;
 17185 
 17186               /* The X error handler may have deleted that frame.  */
 17187               if (!FRAME_LIVE_P (f))
 17188                 continue;
 17189 
 17190               /* Any scroll bars which redisplay_windows should have
 17191                  nuked should now go away.  */
 17192               if (gcscrollbars && FRAME_TERMINAL (f)->judge_scroll_bars_hook)
 17193                 FRAME_TERMINAL (f)->judge_scroll_bars_hook (f);
 17194 
 17195               if (FRAME_REDISPLAY_P (f) && !FRAME_OBSCURED_P (f))
 17196                 {
 17197                   /* If fonts changed on visible frame, display again.  */
 17198                   if (f->fonts_changed)
 17199                     {
 17200                       adjust_frame_glyphs (f);
 17201                       /* Disable all redisplay optimizations for this
 17202                          frame.  For the reasons, see the comment near
 17203                          the previous call to adjust_frame_glyphs above.  */
 17204                       SET_FRAME_GARBAGED (f);
 17205                       f->fonts_changed = false;
 17206                       goto retry_frame;
 17207                     }
 17208 
 17209                   /* See if we have to hscroll.  */
 17210                   if (!f->already_hscrolled_p)
 17211                     {
 17212                       f->already_hscrolled_p = true;
 17213                       if (hscroll_retries <= MAX_HSCROLL_RETRIES
 17214                           && hscroll_windows (f->root_window))
 17215                         {
 17216                           hscroll_retries++;
 17217                           goto retry_frame;
 17218                         }
 17219                     }
 17220 
 17221                   /* If the frame's redisplay flag was not set before
 17222                      we went about redisplaying its windows, but it is
 17223                      set now, that means we employed some redisplay
 17224                      optimizations inside redisplay_windows, and
 17225                      bypassed producing some screen lines.  But if
 17226                      f->redisplay is now set, it might mean the old
 17227                      faces are no longer valid (e.g., if redisplaying
 17228                      some window called some Lisp which defined a new
 17229                      face or redefined an existing face), so trying to
 17230                      use them in update_frame will segfault.
 17231                      Therefore, we must redisplay this frame.  */
 17232                   if (!f_redisplay_flag && f->redisplay)
 17233                     goto retry_frame;
 17234                   /* In some case (e.g., window resize), we notice
 17235                      only during window updating that the window
 17236                      content changed unpredictably (e.g., a GTK
 17237                      scrollbar moved, or some Lisp hook that winds up
 17238                      calling adjust_frame_glyphs) and that our
 17239                      previous estimation of the frame content was
 17240                      garbage.  We have to start over.  These cases
 17241                      should be rare, so going all the way back to the
 17242                      top of redisplay should be good enough.  */
 17243                   if (FRAME_GARBAGED_P (f)
 17244                       && garbaged_frame_retries++ < MAX_GARBAGED_FRAME_RETRIES)
 17245                     goto retry;
 17246 
 17247 #ifdef HAVE_WINDOW_SYSTEM
 17248                   if (FRAME_WINDOW_P (f)
 17249                       && FRAME_RIF (f)->clear_under_internal_border)
 17250                     FRAME_RIF (f)->clear_under_internal_border (f);
 17251 #endif
 17252                   /* Prevent various kinds of signals during display
 17253                      update.  stdio is not robust about handling
 17254                      signals, which can cause an apparent I/O error.  */
 17255                   if (interrupt_input)
 17256                     unrequest_sigio ();
 17257                   STOP_POLLING;
 17258 
 17259                   pending |= update_frame (f, false, false);
 17260                   /* On some platforms (at least MS-Windows), the
 17261                      scroll_run_hook called from scrolling_window
 17262                      called from update_frame could set the frame's
 17263                      garbaged flag, in which case we need to redisplay
 17264                      the frame.  Don't do that on TTY frames, since we
 17265                      need to keep the garbaged flag in that case when
 17266                      the frame has been resized.  */
 17267                   if (FRAME_GARBAGED_P (f))
 17268                     {
 17269                       fset_redisplay (f);
 17270                       f->garbaged = false;
 17271                       goto retry_frame;
 17272                     }
 17273                   f->cursor_type_changed = false;
 17274                   f->updated_p = true;
 17275                   f->inhibit_clear_image_cache = false;
 17276                 }
 17277             }
 17278         }
 17279 
 17280       eassert (EQ (XFRAME (selected_frame)->selected_window, selected_window));
 17281 
 17282       if (!pending)
 17283         {
 17284           /* Do the mark_window_display_accurate after all windows have
 17285              been redisplayed because this call resets flags in buffers
 17286              which are needed for proper redisplay.  */
 17287           FOR_EACH_FRAME (tail, frame)
 17288             {
 17289               struct frame *f = XFRAME (frame);
 17290               if (f->updated_p)
 17291                 {
 17292                   f->redisplay = false;
 17293                   f->garbaged = false;
 17294                   mark_window_display_accurate (f->root_window, true);
 17295                   if (FRAME_TERMINAL (f)->frame_up_to_date_hook)
 17296                     FRAME_TERMINAL (f)->frame_up_to_date_hook (f);
 17297                 }
 17298             }
 17299         }
 17300     }
 17301   else if (FRAME_REDISPLAY_P (sf) && !FRAME_OBSCURED_P (sf))
 17302     {
 17303       sf->inhibit_clear_image_cache = true;
 17304       displayed_buffer = XBUFFER (XWINDOW (selected_window)->contents);
 17305       /* Use list_of_error, not Qerror, so that
 17306          we catch only errors and don't run the debugger.  */
 17307       internal_condition_case_1 (redisplay_window_1, selected_window,
 17308                                  list_of_error,
 17309                                  redisplay_window_error);
 17310       if (update_miniwindow_p)
 17311         {
 17312           Lisp_Object mini_window = FRAME_MINIBUF_WINDOW (sf);
 17313 
 17314           displayed_buffer = XBUFFER (XWINDOW (mini_window)->contents);
 17315           internal_condition_case_1 (redisplay_window_1, mini_window,
 17316                                      list_of_error,
 17317                                      redisplay_window_error);
 17318         }
 17319 
 17320       /* Compare desired and current matrices, perform output.  */
 17321 
 17322     update:
 17323       /* If fonts changed, display again.  Likewise if redisplay_window_1
 17324          above caused some change (e.g., a change in faces) that requires
 17325          considering the entire frame again.  */
 17326       if (sf->fonts_changed || sf->redisplay)
 17327         {
 17328           if (sf->redisplay)
 17329             {
 17330               /* Set this to force a more thorough redisplay.
 17331                  Otherwise, we might immediately loop back to the
 17332                  above "else-if" clause (since all the conditions that
 17333                  led here might still be true), and we will then
 17334                  infloop, because the selected-frame's redisplay flag
 17335                  is not (and cannot be) reset.  */
 17336               windows_or_buffers_changed = 50;
 17337             }
 17338           goto retry;
 17339         }
 17340 
 17341       /* Prevent freeing of realized faces, since desired matrices are
 17342          pending that reference the faces we computed and cached.  */
 17343       inhibit_free_realized_faces = true;
 17344 
 17345       /* Prevent various kinds of signals during display update.
 17346          stdio is not robust about handling signals,
 17347          which can cause an apparent I/O error.  */
 17348       if (interrupt_input)
 17349         unrequest_sigio ();
 17350       STOP_POLLING;
 17351 
 17352       if (FRAME_REDISPLAY_P (sf) && !FRAME_OBSCURED_P (sf))
 17353         {
 17354           if (hscroll_retries <= MAX_HSCROLL_RETRIES
 17355               && hscroll_windows (selected_window))
 17356             {
 17357               hscroll_retries++;
 17358               goto retry;
 17359             }
 17360 
 17361           XWINDOW (selected_window)->must_be_updated_p = true;
 17362           pending = update_frame (sf, false, false);
 17363           sf->cursor_type_changed = false;
 17364           sf->inhibit_clear_image_cache = false;
 17365         }
 17366 
 17367       /* We may have called echo_area_display at the top of this
 17368          function.  If the echo area is on another frame, that may
 17369          have put text on a frame other than the selected one, so the
 17370          above call to update_frame would not have caught it.  Catch
 17371          it here.  */
 17372       Lisp_Object mini_window = FRAME_MINIBUF_WINDOW (sf);
 17373       struct frame *mini_frame = XFRAME (WINDOW_FRAME (XWINDOW (mini_window)));
 17374 
 17375       if (mini_frame != sf && FRAME_WINDOW_P (mini_frame))
 17376         {
 17377           XWINDOW (mini_window)->must_be_updated_p = true;
 17378           pending |= update_frame (mini_frame, false, false);
 17379           mini_frame->cursor_type_changed = false;
 17380           if (!pending && hscroll_retries <= MAX_HSCROLL_RETRIES
 17381               && hscroll_windows (mini_window))
 17382             {
 17383               hscroll_retries++;
 17384               goto retry;
 17385             }
 17386         }
 17387     }
 17388 
 17389   /* If display was paused because of pending input, make sure we do a
 17390      thorough update the next time.  */
 17391   if (pending)
 17392     {
 17393       /* Prevent the optimization at the beginning of
 17394          redisplay_internal that tries a single-line update of the
 17395          line containing the cursor in the selected window.  */
 17396       CHARPOS (this_line_start_pos) = 0;
 17397 
 17398       /* Let the overlay arrow be updated the next time.  */
 17399       update_overlay_arrows (0);
 17400 
 17401       /* If we pause after scrolling, some rows in the current
 17402          matrices of some windows are not valid.  */
 17403       if (!WINDOW_FULL_WIDTH_P (w)
 17404           && !FRAME_WINDOW_P (XFRAME (w->frame)))
 17405         update_mode_lines = 36;
 17406     }
 17407   else
 17408     {
 17409       if (!consider_all_windows_p)
 17410         {
 17411           /* This has already been done above if
 17412              consider_all_windows_p is set.  */
 17413           if (XBUFFER (w->contents)->text->redisplay
 17414               && buffer_window_count (XBUFFER (w->contents)) > 1)
 17415             /* This can happen if b->text->redisplay was set during
 17416                jit-lock.  */
 17417             propagate_buffer_redisplay ();
 17418           mark_window_display_accurate_1 (w, true);
 17419 
 17420           /* Say overlay arrows are up to date.  */
 17421           update_overlay_arrows (1);
 17422 
 17423           if (FRAME_TERMINAL (sf)->frame_up_to_date_hook != 0)
 17424             FRAME_TERMINAL (sf)->frame_up_to_date_hook (sf);
 17425         }
 17426 
 17427       update_mode_lines = 0;
 17428       windows_or_buffers_changed = 0;
 17429     }
 17430 
 17431   /* Start SIGIO interrupts coming again.  Having them off during the
 17432      code above makes it less likely one will discard output, but not
 17433      impossible, since there might be stuff in the system buffer here.
 17434      But it is much hairier to try to do anything about that.  */
 17435   if (interrupt_input)
 17436     request_sigio ();
 17437   RESUME_POLLING;
 17438 
 17439   /* If a frame has become visible which was not before, redisplay
 17440      again, so that we display it.  Expose events for such a frame
 17441      (which it gets when becoming visible) don't call the parts of
 17442      redisplay constructing glyphs, so simply exposing a frame won't
 17443      display anything in this case.  So, we have to display these
 17444      frames here explicitly.  */
 17445   if (!pending)
 17446     {
 17447       int new_count = 0;
 17448 
 17449       FOR_EACH_FRAME (tail, frame)
 17450         {
 17451           if (FRAME_REDISPLAY_P (XFRAME (frame)))
 17452             new_count++;
 17453         }
 17454 
 17455       if (new_count != number_of_visible_frames)
 17456         windows_or_buffers_changed = 52;
 17457     }
 17458 
 17459   /* Change frame size now if a change is pending.  */
 17460   do_pending_window_change (true);
 17461 
 17462   /* If we just did a pending size change, or have additional
 17463      visible frames, or selected_window changed, redisplay again.  */
 17464   if ((windows_or_buffers_changed && !pending)
 17465       || (WINDOWP (selected_window)
 17466           && (w = XWINDOW (selected_window)) != sw))
 17467     goto retry;
 17468 
 17469   /* Clear the face and image caches.
 17470 
 17471      We used to do this only if consider_all_windows_p.  But the cache
 17472      needs to be cleared if a timer creates images in the current
 17473      buffer (e.g. the test case in Bug#6230).  */
 17474 
 17475   if (clear_face_cache_count > CLEAR_FACE_CACHE_COUNT)
 17476     {
 17477       clear_face_cache (false);
 17478       clear_face_cache_count = 0;
 17479     }
 17480 
 17481 #ifdef HAVE_WINDOW_SYSTEM
 17482   if (clear_image_cache_count > CLEAR_IMAGE_CACHE_COUNT)
 17483     {
 17484       clear_image_caches (Qnil);
 17485       clear_image_cache_count = 0;
 17486     }
 17487 #endif /* HAVE_WINDOW_SYSTEM */
 17488 
 17489  end_of_redisplay:
 17490 #ifdef HAVE_NS
 17491   ns_set_doc_edited ();
 17492 #endif
 17493   if (interrupt_input && interrupts_deferred)
 17494     request_sigio ();
 17495 
 17496   /* We're done with this redisplay cycle, so reset the tick count in
 17497      preparation for the next redisplay cycle.  */
 17498   if (max_redisplay_ticks > 0)
 17499     update_redisplay_ticks (0, NULL);
 17500 
 17501   unbind_to (count, Qnil);
 17502   RESUME_POLLING;
 17503 }
 17504 
 17505 static void
 17506 unwind_redisplay_preserve_echo_area (void)
 17507 {
 17508   unblock_buffer_flips ();
 17509 }
 17510 
 17511 /* Redisplay, but leave alone any recent echo area message unless
 17512    another message has been requested in its place.
 17513 
 17514    This is useful in situations where you need to redisplay but no
 17515    user action has occurred, making it inappropriate for the message
 17516    area to be cleared.  See tracking_off and
 17517    wait_reading_process_output for examples of these situations.
 17518 
 17519    FROM_WHERE is an integer saying from where this function was
 17520    called.  This is useful for debugging.  */
 17521 
 17522 void
 17523 redisplay_preserve_echo_area (int from_where)
 17524 {
 17525   redisplay_trace ("redisplay_preserve_echo_area (%d)\n", from_where);
 17526 
 17527   block_input ();
 17528   specpdl_ref count = SPECPDL_INDEX ();
 17529   record_unwind_protect_void (unwind_redisplay_preserve_echo_area);
 17530   block_buffer_flips ();
 17531   unblock_input ();
 17532 
 17533   if (!NILP (echo_area_buffer[1]))
 17534     {
 17535       /* We have a previously displayed message, but no current
 17536          message.  Redisplay the previous message.  */
 17537       display_last_displayed_message_p = true;
 17538       redisplay_internal ();
 17539       display_last_displayed_message_p = false;
 17540     }
 17541   else
 17542     redisplay_internal ();
 17543 
 17544   flush_frame (SELECTED_FRAME ());
 17545   unbind_to (count, Qnil);
 17546 }
 17547 
 17548 
 17549 /* Function registered with record_unwind_protect in redisplay_internal.  */
 17550 
 17551 static void
 17552 unwind_redisplay (void)
 17553 {
 17554   redisplaying_p = false;
 17555   unblock_buffer_flips ();
 17556 }
 17557 
 17558 /* Function registered with record_unwind_protect before calling
 17559    start_display outside of redisplay_internal.  */
 17560 void
 17561 unwind_display_working_on_window (void)
 17562 {
 17563   display_working_on_window_p = false;
 17564 }
 17565 
 17566 /* Mark the display of leaf window W as accurate or inaccurate.
 17567    If ACCURATE_P, mark display of W as accurate.
 17568    If !ACCURATE_P, arrange for W to be redisplayed the next
 17569    time redisplay_internal is called.  */
 17570 
 17571 static void
 17572 mark_window_display_accurate_1 (struct window *w, bool accurate_p)
 17573 {
 17574   struct buffer *b = XBUFFER (w->contents);
 17575 #ifdef HAVE_TEXT_CONVERSION
 17576   ptrdiff_t prev_point, prev_mark;
 17577 #endif /* HAVE_TEXT_CONVERSION */
 17578 
 17579   w->last_modified = accurate_p ? BUF_MODIFF (b) : 0;
 17580   w->last_overlay_modified = accurate_p ? BUF_OVERLAY_MODIFF (b) : 0;
 17581   w->last_had_star = BUF_MODIFF (b) > BUF_SAVE_MODIFF (b);
 17582 
 17583   if (accurate_p)
 17584     {
 17585       b->clip_changed = false;
 17586       b->prevent_redisplay_optimizations_p = false;
 17587       eassert (buffer_window_count (b) > 0);
 17588       /* Resetting b->text->redisplay is problematic!
 17589          In order to make it safer to do it here, redisplay_internal must
 17590          have copied all b->text->redisplay to their respective windows.  */
 17591       b->text->redisplay = false;
 17592 
 17593       BUF_UNCHANGED_MODIFIED (b) = BUF_MODIFF (b);
 17594       BUF_OVERLAY_UNCHANGED_MODIFIED (b) = BUF_OVERLAY_MODIFF (b);
 17595       BUF_BEG_UNCHANGED (b) = BUF_GPT (b) - BUF_BEG (b);
 17596       BUF_END_UNCHANGED (b) = BUF_Z (b) - BUF_GPT (b);
 17597 
 17598       w->current_matrix->buffer = b;
 17599       w->current_matrix->begv = BUF_BEGV (b);
 17600       w->current_matrix->zv = BUF_ZV (b);
 17601       w->current_matrix->header_line_p = window_wants_header_line (w);
 17602       w->current_matrix->tab_line_p = window_wants_tab_line (w);
 17603 
 17604       w->last_cursor_vpos = w->cursor.vpos;
 17605       w->last_cursor_off_p = w->cursor_off_p;
 17606 
 17607 #ifdef HAVE_TEXT_CONVERSION
 17608       prev_point = w->last_point;
 17609       prev_mark = w->last_mark;
 17610 #endif /* HAVE_TEXT_CONVERSION */
 17611 
 17612       if (w == XWINDOW (selected_window))
 17613         w->last_point = BUF_PT (b);
 17614       else
 17615         w->last_point = marker_position (w->pointm);
 17616 
 17617       /* w->last_mark is recorded for text conversion purposes.
 17618          Input methods aren't interested in the value of the mark
 17619          if it is inactive, so set it to -1 if it's not.  */
 17620 
 17621       if (XMARKER (BVAR (b, mark))->buffer == b
 17622           && !NILP (BVAR (b, mark_active)))
 17623         w->last_mark = marker_position (BVAR (b, mark));
 17624       else
 17625         w->last_mark = -1;
 17626 
 17627 #ifdef HAVE_TEXT_CONVERSION
 17628       /* See the description of this field in struct window.  */
 17629       w->ephemeral_last_point = w->last_point;
 17630 
 17631       /* Point motion is only propagated to the input method for use
 17632          in text conversion during a redisplay.  While this can lead
 17633          to inconsistencies when point has moved but the change has
 17634          not yet been displayed, it leads to better results most of
 17635          the time, as point often changes within calls to
 17636          `save-excursion', and the only way to detect such calls is to
 17637          observe that the next redisplay never ends with those changes
 17638          applied.
 17639 
 17640          Changes to buffer text are immediately propagated to the
 17641          input method, and the position of point is also updated
 17642          during such a change, so the consequences are not that
 17643          severe.  */
 17644 
 17645       if ((prev_point != w->last_point
 17646            || prev_mark != w->last_mark)
 17647           && FRAME_WINDOW_P (WINDOW_XFRAME (w))
 17648           && w == XWINDOW (WINDOW_XFRAME (w)->selected_window))
 17649         report_point_change (WINDOW_XFRAME (w), w, b);
 17650 #endif /* HAVE_TEXT_CONVERSION */
 17651 
 17652       w->window_end_valid = true;
 17653       w->update_mode_line = false;
 17654       w->preserve_vscroll_p = false;
 17655     }
 17656 
 17657   w->redisplay = !accurate_p;
 17658 }
 17659 
 17660 
 17661 /* Mark the display of windows in the window tree rooted at WINDOW as
 17662    accurate or inaccurate.  If ACCURATE_P, mark display of
 17663    windows as accurate.  If !ACCURATE_P, arrange for windows to
 17664    be redisplayed the next time redisplay_internal is called.  */
 17665 
 17666 void
 17667 mark_window_display_accurate (Lisp_Object window, bool accurate_p)
 17668 {
 17669   struct window *w;
 17670 
 17671   for (; !NILP (window); window = w->next)
 17672     {
 17673       w = XWINDOW (window);
 17674       if (WINDOWP (w->contents))
 17675         mark_window_display_accurate (w->contents, accurate_p);
 17676       else
 17677         mark_window_display_accurate_1 (w, accurate_p);
 17678     }
 17679 
 17680   if (accurate_p)
 17681     update_overlay_arrows (1);
 17682   else
 17683     /* Force a thorough redisplay the next time by setting
 17684        last_arrow_position and last_arrow_string to t, which is
 17685        unequal to any useful value of Voverlay_arrow_...  */
 17686     update_overlay_arrows (-1);
 17687 }
 17688 
 17689 
 17690 /* Return value in display table DP (Lisp_Char_Table *) for character
 17691    C.  Since a display table doesn't have any parent, we don't have to
 17692    follow parent.  Do not call this function directly but use the
 17693    macro DISP_CHAR_VECTOR.  */
 17694 
 17695 Lisp_Object
 17696 disp_char_vector (struct Lisp_Char_Table *dp, int c)
 17697 {
 17698   Lisp_Object val;
 17699 
 17700   if (ASCII_CHAR_P (c))
 17701     {
 17702       val = dp->ascii;
 17703       if (SUB_CHAR_TABLE_P (val))
 17704         val = XSUB_CHAR_TABLE (val)->contents[c];
 17705     }
 17706   else
 17707     {
 17708       Lisp_Object table;
 17709 
 17710       XSETCHAR_TABLE (table, dp);
 17711       val = char_table_ref (table, c);
 17712     }
 17713   if (NILP (val))
 17714     val = dp->defalt;
 17715   return val;
 17716 }
 17717 
 17718 static int buffer_flip_blocked_depth;
 17719 
 17720 static void
 17721 block_buffer_flips (void)
 17722 {
 17723   eassert (buffer_flip_blocked_depth >= 0);
 17724   buffer_flip_blocked_depth++;
 17725 }
 17726 
 17727 static void
 17728 unblock_buffer_flips (void)
 17729 {
 17730   eassert (buffer_flip_blocked_depth > 0);
 17731   if (--buffer_flip_blocked_depth == 0)
 17732     {
 17733       Lisp_Object tail, frame;
 17734       block_input ();
 17735       FOR_EACH_FRAME (tail, frame)
 17736         {
 17737           struct frame *f = XFRAME (frame);
 17738           if (FRAME_TERMINAL (f)->buffer_flipping_unblocked_hook)
 17739             (*FRAME_TERMINAL (f)->buffer_flipping_unblocked_hook) (f);
 17740         }
 17741       unblock_input ();
 17742     }
 17743 }
 17744 
 17745 bool
 17746 buffer_flipping_blocked_p (void)
 17747 {
 17748   return buffer_flip_blocked_depth > 0;
 17749 }
 17750 
 17751 
 17752 /***********************************************************************
 17753                            Window Redisplay
 17754  ***********************************************************************/
 17755 
 17756 /* Redisplay all leaf windows in the window tree rooted at WINDOW.  */
 17757 
 17758 static void
 17759 redisplay_windows (Lisp_Object window)
 17760 {
 17761   while (!NILP (window))
 17762     {
 17763       struct window *w = XWINDOW (window);
 17764 
 17765       if (WINDOWP (w->contents))
 17766         redisplay_windows (w->contents);
 17767       else if (BUFFERP (w->contents))
 17768         {
 17769           displayed_buffer = XBUFFER (w->contents);
 17770           /* Use list_of_error, not Qerror, so that
 17771              we catch only errors and don't run the debugger.  */
 17772           internal_condition_case_1 (redisplay_window_0, window,
 17773                                      list_of_error,
 17774                                      redisplay_window_error);
 17775         }
 17776 
 17777       window = w->next;
 17778     }
 17779 }
 17780 
 17781 static Lisp_Object
 17782 redisplay_window_error (Lisp_Object error_data)
 17783 {
 17784   displayed_buffer->display_error_modiff = BUF_MODIFF (displayed_buffer);
 17785 
 17786   /* When in redisplay, the error is captured and not shown.  Arrange
 17787      for it to be shown later.  */
 17788   if (max_redisplay_ticks > 0
 17789       && CONSP (error_data)
 17790       && EQ (XCAR (error_data), Qerror)
 17791       && STRINGP (XCAR (XCDR (error_data))))
 17792     Vdelayed_warnings_list = Fcons (list2 (XCAR (error_data),
 17793                                            XCAR (XCDR (error_data))),
 17794                                     Vdelayed_warnings_list);
 17795   return Qnil;
 17796 }
 17797 
 17798 static Lisp_Object
 17799 redisplay_window_0 (Lisp_Object window)
 17800 {
 17801   if (displayed_buffer->display_error_modiff < BUF_MODIFF (displayed_buffer))
 17802     redisplay_window (window, false);
 17803   return Qnil;
 17804 }
 17805 
 17806 static Lisp_Object
 17807 redisplay_window_1 (Lisp_Object window)
 17808 {
 17809   if (displayed_buffer->display_error_modiff < BUF_MODIFF (displayed_buffer))
 17810     redisplay_window (window, true);
 17811   return Qnil;
 17812 }
 17813 
 17814 
 17815 /***********************************************************************
 17816                       Aborting runaway redisplay
 17817  ***********************************************************************/
 17818 
 17819 /* Update the redisplay-tick count for window W, and signal an error
 17820    if the tick count is above some threshold, indicating that
 17821    redisplay of the window takes "too long".
 17822 
 17823    TICKS is the amount of ticks to add to the W's current count; zero
 17824    means to initialize the tick count to zero.
 17825 
 17826    W can be NULL if TICKS is zero: that means unconditionally
 17827    re-initialize the current tick count to zero.
 17828 
 17829    W can also be NULL if the caller doesn't know which window is being
 17830    processed by the display code.  In that case, if TICKS is non-zero,
 17831    we assume it's the last window that shows the current buffer.  */
 17832 void
 17833 update_redisplay_ticks (int ticks, struct window *w)
 17834 {
 17835   /* This keeps track of the window on which redisplay is working.  */
 17836   static struct window *cwindow;
 17837   static EMACS_INT window_ticks;
 17838 
 17839   /* We only initialize the count if this is a different window or
 17840      NULL.  Otherwise, this is a call from init_iterator for the same
 17841      window we tracked before, and we should keep the count.  */
 17842   if (!ticks && w != cwindow)
 17843     {
 17844       cwindow = w;
 17845       window_ticks = 0;
 17846     }
 17847   /* Some callers can be run in contexts unrelated to display code, so
 17848      don't abort them and don't update the tick count in those cases.  */
 17849   if ((!w && !redisplaying_p && !display_working_on_window_p)
 17850       /* We never disable redisplay of a mini-window, since that is
 17851          absolutely essential for communicating with Emacs.  */
 17852       || (w && MINI_WINDOW_P (w)))
 17853     return;
 17854 
 17855   if (ticks > 0)
 17856     window_ticks += ticks;
 17857   if (max_redisplay_ticks > 0 && window_ticks > max_redisplay_ticks)
 17858     {
 17859       /* In addition to a buffer, this could be a window (for non-leaf
 17860          windows, not expected here) or nil (for pseudo-windows like
 17861          the one used for the native tool bar).  */
 17862       Lisp_Object contents = w ? w->contents : Qnil;
 17863       char *bufname =
 17864         NILP (contents)
 17865         ? SSDATA (BVAR (current_buffer, name))
 17866         : (BUFFERP (contents)
 17867            ? SSDATA (BVAR (XBUFFER (contents), name))
 17868            : (char *) "<unknown>");
 17869 
 17870       windows_or_buffers_changed = 177;
 17871       /* scrolling_window depends too much on the glyph matrices being
 17872          correct, and we cannot guarantee that if we abort the
 17873          redisplay of this window.  */
 17874       if (w && w->desired_matrix)
 17875         w->desired_matrix->no_scrolling_p = true;
 17876       error ("Window showing buffer %s takes too long to redisplay", bufname);
 17877     }
 17878 }
 17879 
 17880 
 17881 
 17882 /* Set cursor position of W.  PT is assumed to be displayed in ROW.
 17883    DELTA and DELTA_BYTES are the numbers of characters and bytes by
 17884    which positions recorded in ROW differ from current buffer
 17885    positions.
 17886 
 17887    Return true iff cursor is on this row.  */
 17888 
 17889 static bool
 17890 set_cursor_from_row (struct window *w, struct glyph_row *row,
 17891                      struct glyph_matrix *matrix,
 17892                      ptrdiff_t delta, ptrdiff_t delta_bytes,
 17893                      int dy, int dvpos)
 17894 {
 17895   struct glyph *glyph = row->glyphs[TEXT_AREA];
 17896   struct glyph *end = glyph + row->used[TEXT_AREA];
 17897   struct glyph *cursor = NULL;
 17898   /* The last known character position in row.  */
 17899   ptrdiff_t last_pos = MATRIX_ROW_START_CHARPOS (row) + delta;
 17900   int x = row->x;
 17901   ptrdiff_t pt_old = PT - delta;
 17902   ptrdiff_t pos_before = MATRIX_ROW_START_CHARPOS (row) + delta;
 17903   ptrdiff_t pos_after = MATRIX_ROW_END_CHARPOS (row) + delta;
 17904   struct glyph *glyph_before = glyph - 1, *glyph_after = end;
 17905   /* A glyph beyond the edge of TEXT_AREA which we should never
 17906      touch.  */
 17907   struct glyph *glyphs_end = end;
 17908   /* True means we've found a match for cursor position, but that
 17909      glyph has the avoid_cursor_p flag set.  */
 17910   bool match_with_avoid_cursor = false;
 17911   /* True means we've seen at least one glyph that came from a
 17912      display string.  */
 17913   bool string_seen = false;
 17914   /* Largest and smallest buffer positions seen so far during scan of
 17915      glyph row.  */
 17916   ptrdiff_t bpos_max = pos_before;
 17917   ptrdiff_t bpos_min = pos_after;
 17918   /* Last buffer position covered by an overlay string with an integer
 17919      `cursor' property.  */
 17920   ptrdiff_t bpos_covered = 0;
 17921   /* True means the display string on which to display the cursor
 17922      comes from a text property, not from an overlay.  */
 17923   bool string_from_text_prop = false;
 17924 
 17925   /* Don't even try doing anything if called for a mode-line or
 17926      header-line or tab-line row, since the rest of the code isn't
 17927      prepared to deal with such calamities.  */
 17928   eassert (!row->mode_line_p);
 17929   if (row->mode_line_p)
 17930     return false;
 17931 
 17932   /* Skip over glyphs not having an object at the start and the end of
 17933      the row.  These are special glyphs like truncation marks on
 17934      terminal frames.  */
 17935   if (MATRIX_ROW_DISPLAYS_TEXT_P (row))
 17936     {
 17937       if (!row->reversed_p)
 17938         {
 17939           while (glyph < end
 17940                  && NILP (glyph->object)
 17941                  && glyph->charpos < 0)
 17942             {
 17943               x += glyph->pixel_width;
 17944               ++glyph;
 17945             }
 17946           while (end > glyph
 17947                  && NILP ((end - 1)->object)
 17948                  /* CHARPOS is zero for blanks and stretch glyphs
 17949                     inserted by extend_face_to_end_of_line.  */
 17950                  && (end - 1)->charpos <= 0)
 17951             --end;
 17952           glyph_before = glyph - 1;
 17953           glyph_after = end;
 17954         }
 17955       else
 17956         {
 17957           struct glyph *g;
 17958 
 17959           /* If the glyph row is reversed, we need to process it from back
 17960              to front, so swap the edge pointers.  */
 17961           glyphs_end = end = glyph - 1;
 17962           glyph += row->used[TEXT_AREA] - 1;
 17963 
 17964           while (glyph > end + 1
 17965                  && NILP (glyph->object)
 17966                  && glyph->charpos < 0)
 17967             --glyph;
 17968           if (NILP (glyph->object) && glyph->charpos < 0)
 17969             --glyph;
 17970           /* By default, in reversed rows we put the cursor on the
 17971              rightmost (first in the reading order) glyph.  */
 17972           for (x = 0, g = end + 1; g < glyph; g++)
 17973             x += g->pixel_width;
 17974           while (end < glyph
 17975                  && NILP ((end + 1)->object)
 17976                  && (end + 1)->charpos <= 0)
 17977             ++end;
 17978           glyph_before = glyph + 1;
 17979           glyph_after = end;
 17980         }
 17981     }
 17982   else if (row->reversed_p)
 17983     {
 17984       /* In R2L rows that don't display text, put the cursor on the
 17985          rightmost glyph.  Case in point: an empty last line that is
 17986          part of an R2L paragraph.  */
 17987       cursor = end - 1;
 17988       /* Avoid placing the cursor on the last glyph of the row, where
 17989          on terminal frames we hold the vertical border between
 17990          adjacent windows.  */
 17991       if (!FRAME_WINDOW_P (WINDOW_XFRAME (w))
 17992           && !WINDOW_RIGHTMOST_P (w)
 17993           && cursor == row->glyphs[LAST_AREA] - 1)
 17994         cursor--;
 17995       x = -1;   /* will be computed below, at label compute_x */
 17996     }
 17997 
 17998   /* Step 1: Try to find the glyph whose character position
 17999      corresponds to point.  If that's not possible, find 2 glyphs
 18000      whose character positions are the closest to point, one before
 18001      point, the other after it.  */
 18002   if (!row->reversed_p)
 18003     while (/* not marched to end of glyph row */
 18004            glyph < end
 18005            /* glyph was not inserted by redisplay for internal purposes */
 18006            && !NILP (glyph->object))
 18007       {
 18008         if (BUFFERP (glyph->object))
 18009           {
 18010             ptrdiff_t dpos = glyph->charpos - pt_old;
 18011 
 18012             if (glyph->charpos > bpos_max)
 18013               bpos_max = glyph->charpos;
 18014             if (glyph->charpos < bpos_min)
 18015               bpos_min = glyph->charpos;
 18016             if (!glyph->avoid_cursor_p)
 18017               {
 18018                 /* If we hit point, we've found the glyph on which to
 18019                    display the cursor.  */
 18020                 if (dpos == 0)
 18021                   {
 18022                     match_with_avoid_cursor = false;
 18023                     break;
 18024                   }
 18025                 /* See if we've found a better approximation to
 18026                    POS_BEFORE or to POS_AFTER.  */
 18027                 if (0 > dpos && dpos > pos_before - pt_old)
 18028                   {
 18029                     pos_before = glyph->charpos;
 18030                     glyph_before = glyph;
 18031                   }
 18032                 else if (0 < dpos && dpos < pos_after - pt_old)
 18033                   {
 18034                     pos_after = glyph->charpos;
 18035                     glyph_after = glyph;
 18036                   }
 18037               }
 18038             else if (dpos == 0)
 18039               match_with_avoid_cursor = true;
 18040           }
 18041         else if (STRINGP (glyph->object))
 18042           {
 18043             Lisp_Object chprop;
 18044             ptrdiff_t glyph_pos = glyph->charpos;
 18045 
 18046             chprop = Fget_char_property (make_fixnum (glyph_pos), Qcursor,
 18047                                          glyph->object);
 18048             if (!NILP (chprop))
 18049               {
 18050                 /* If the string came from a `display' text property,
 18051                    look up the buffer position of that property and
 18052                    use that position to update bpos_max, as if we
 18053                    actually saw such a position in one of the row's
 18054                    glyphs.  This helps with supporting integer values
 18055                    of `cursor' property on the display string in
 18056                    situations where most or all of the row's buffer
 18057                    text is completely covered by display properties,
 18058                    so that no glyph with valid buffer positions is
 18059                    ever seen in the row.  */
 18060                 ptrdiff_t prop_pos =
 18061                   string_buffer_position_lim (glyph->object, pos_before,
 18062                                               pos_after, false);
 18063 
 18064                 if (prop_pos >= pos_before)
 18065                   bpos_max = prop_pos;
 18066               }
 18067             if (FIXNUMP (chprop))
 18068               {
 18069                 bpos_covered = bpos_max + XFIXNUM (chprop);
 18070                 /* If the `cursor' property covers buffer positions up
 18071                    to and including point, we should display cursor on
 18072                    this glyph.  Note that, if a `cursor' property on one
 18073                    of the string's characters has an integer value, we
 18074                    will break out of the loop below _before_ we get to
 18075                    the position match above.  IOW, integer values of
 18076                    the `cursor' property override the "exact match for
 18077                    point" strategy of positioning the cursor.  */
 18078                 /* Implementation note: bpos_max == pt_old when, e.g.,
 18079                    we are in an empty line, where bpos_max is set to
 18080                    MATRIX_ROW_START_CHARPOS, see above.  */
 18081                 if (bpos_max <= pt_old && bpos_covered >= pt_old)
 18082                   {
 18083                     cursor = glyph;
 18084                     break;
 18085                   }
 18086               }
 18087 
 18088             string_seen = true;
 18089           }
 18090         x += glyph->pixel_width;
 18091         ++glyph;
 18092       }
 18093   else if (glyph > end) /* row is reversed */
 18094     while (!NILP (glyph->object))
 18095       {
 18096         if (BUFFERP (glyph->object))
 18097           {
 18098             ptrdiff_t dpos = glyph->charpos - pt_old;
 18099 
 18100             if (glyph->charpos > bpos_max)
 18101               bpos_max = glyph->charpos;
 18102             if (glyph->charpos < bpos_min)
 18103               bpos_min = glyph->charpos;
 18104             if (!glyph->avoid_cursor_p)
 18105               {
 18106                 if (dpos == 0)
 18107                   {
 18108                     match_with_avoid_cursor = false;
 18109                     break;
 18110                   }
 18111                 if (0 > dpos && dpos > pos_before - pt_old)
 18112                   {
 18113                     pos_before = glyph->charpos;
 18114                     glyph_before = glyph;
 18115                   }
 18116                 else if (0 < dpos && dpos < pos_after - pt_old)
 18117                   {
 18118                     pos_after = glyph->charpos;
 18119                     glyph_after = glyph;
 18120                   }
 18121               }
 18122             else if (dpos == 0)
 18123               match_with_avoid_cursor = true;
 18124           }
 18125         else if (STRINGP (glyph->object))
 18126           {
 18127             Lisp_Object chprop;
 18128             ptrdiff_t glyph_pos = glyph->charpos;
 18129 
 18130             chprop = Fget_char_property (make_fixnum (glyph_pos), Qcursor,
 18131                                          glyph->object);
 18132             if (!NILP (chprop))
 18133               {
 18134                 ptrdiff_t prop_pos =
 18135                   string_buffer_position_lim (glyph->object, pos_before,
 18136                                               pos_after, false);
 18137 
 18138                 if (prop_pos >= pos_before)
 18139                   bpos_max = prop_pos;
 18140               }
 18141             if (FIXNUMP (chprop))
 18142               {
 18143                 bpos_covered = bpos_max + XFIXNUM (chprop);
 18144                 /* If the `cursor' property covers buffer positions up
 18145                    to and including point, we should display cursor on
 18146                    this glyph.  */
 18147                 if (bpos_max <= pt_old && bpos_covered >= pt_old)
 18148                   {
 18149                     cursor = glyph;
 18150                     break;
 18151                   }
 18152               }
 18153             string_seen = true;
 18154           }
 18155         --glyph;
 18156         if (glyph == glyphs_end) /* don't dereference outside TEXT_AREA */
 18157           {
 18158             x--;                /* can't use any pixel_width */
 18159             break;
 18160           }
 18161         x -= glyph->pixel_width;
 18162     }
 18163 
 18164   /* Step 2: If we didn't find an exact match for point, we need to
 18165      look for a proper place to put the cursor among glyphs between
 18166      GLYPH_BEFORE and GLYPH_AFTER.  */
 18167   if (!((row->reversed_p ? glyph > glyphs_end : glyph < glyphs_end)
 18168         && BUFFERP (glyph->object) && glyph->charpos == pt_old)
 18169       && !(bpos_max <= pt_old && pt_old <= bpos_covered))
 18170     {
 18171       /* An empty line has a single glyph whose OBJECT is nil and
 18172          whose CHARPOS is the position of a newline on that line.
 18173          Note that on a TTY, there are more glyphs after that, which
 18174          were produced by extend_face_to_end_of_line, but their
 18175          CHARPOS is zero or negative.  */
 18176       bool empty_line_p =
 18177         ((row->reversed_p ? glyph > glyphs_end : glyph < glyphs_end)
 18178          && NILP (glyph->object) && glyph->charpos > 0
 18179          /* On a TTY, continued and truncated rows also have a glyph at
 18180             their end whose OBJECT is nil and whose CHARPOS is
 18181             positive (the continuation and truncation glyphs), but such
 18182             rows are obviously not "empty".  */
 18183          && !(row->continued_p || row->truncated_on_right_p));
 18184 
 18185       if (row->ends_in_ellipsis_p && pos_after == last_pos)
 18186         {
 18187           ptrdiff_t ellipsis_pos;
 18188 
 18189           /* Scan back over the ellipsis glyphs.  */
 18190           if (!row->reversed_p)
 18191             {
 18192               ellipsis_pos = (glyph - 1)->charpos;
 18193               while (glyph > row->glyphs[TEXT_AREA]
 18194                      && (glyph - 1)->charpos == ellipsis_pos)
 18195                 glyph--, x -= glyph->pixel_width;
 18196               /* That loop always goes one position too far, including
 18197                  the glyph before the ellipsis.  So scan forward over
 18198                  that one.  */
 18199               x += glyph->pixel_width;
 18200               glyph++;
 18201             }
 18202           else  /* row is reversed */
 18203             {
 18204               ellipsis_pos = (glyph + 1)->charpos;
 18205               while (glyph < row->glyphs[TEXT_AREA] + row->used[TEXT_AREA] - 1
 18206                      && (glyph + 1)->charpos == ellipsis_pos)
 18207                 glyph++, x += glyph->pixel_width;
 18208               x -= glyph->pixel_width;
 18209               glyph--;
 18210             }
 18211         }
 18212       else if (match_with_avoid_cursor)
 18213         {
 18214           cursor = glyph_after;
 18215           x = -1;
 18216         }
 18217       else if (string_seen)
 18218         {
 18219           int incr = row->reversed_p ? -1 : +1;
 18220 
 18221           /* Need to find the glyph that came out of a string which is
 18222              present at point.  That glyph is somewhere between
 18223              GLYPH_BEFORE and GLYPH_AFTER, and it came from a string
 18224              positioned between POS_BEFORE and POS_AFTER in the
 18225              buffer.  */
 18226           struct glyph *start, *stop;
 18227           ptrdiff_t pos = pos_before;
 18228 
 18229           x = -1;
 18230 
 18231           /* If the row ends in a newline from a display string,
 18232              reordering could have moved the glyphs belonging to the
 18233              string out of the [GLYPH_BEFORE..GLYPH_AFTER] range.  So
 18234              in this case we extend the search to the last glyph in
 18235              the row that was not inserted by redisplay.  */
 18236           if (row->ends_in_newline_from_string_p)
 18237             {
 18238               glyph_after = end;
 18239               pos_after = MATRIX_ROW_END_CHARPOS (row) + delta;
 18240             }
 18241 
 18242           /* GLYPH_BEFORE and GLYPH_AFTER are the glyphs that
 18243              correspond to POS_BEFORE and POS_AFTER, respectively.  We
 18244              need START and STOP in the order that corresponds to the
 18245              row's direction as given by its reversed_p flag.  If the
 18246              directionality of characters between POS_BEFORE and
 18247              POS_AFTER is the opposite of the row's base direction,
 18248              these characters will have been reordered for display,
 18249              and we need to reverse START and STOP.  */
 18250           if (!row->reversed_p)
 18251             {
 18252               start = min (glyph_before, glyph_after);
 18253               stop = max (glyph_before, glyph_after);
 18254             }
 18255           else
 18256             {
 18257               start = max (glyph_before, glyph_after);
 18258               stop = min (glyph_before, glyph_after);
 18259             }
 18260           for (glyph = start + incr;
 18261                row->reversed_p ? glyph > stop : glyph < stop; )
 18262             {
 18263 
 18264               /* Any glyphs that come from the buffer are here because
 18265                  of bidi reordering.  Skip them, and only pay
 18266                  attention to glyphs that came from some string.  */
 18267               if (STRINGP (glyph->object))
 18268                 {
 18269                   Lisp_Object str;
 18270                   ptrdiff_t tem;
 18271                   /* If the display property covers the newline, we
 18272                      need to search for it one position farther.  */
 18273                   ptrdiff_t lim = pos_after
 18274                     + (pos_after == MATRIX_ROW_END_CHARPOS (row) + delta);
 18275 
 18276                   string_from_text_prop = false;
 18277                   str = glyph->object;
 18278                   tem = string_buffer_position_lim (str, pos, lim, false);
 18279                   if (tem == 0  /* from overlay */
 18280                       || pos <= tem)
 18281                     {
 18282                       /* If the string from which this glyph came is
 18283                          found in the buffer at point, or at position
 18284                          that is closer to point than pos_after, then
 18285                          we've found the glyph we've been looking for.
 18286                          If it comes from an overlay (tem == 0), and
 18287                          it has the `cursor' property on one of its
 18288                          glyphs, record that glyph as a candidate for
 18289                          displaying the cursor.  (As in the
 18290                          unidirectional version, we will display the
 18291                          cursor on the last candidate we find.)  */
 18292                       if (tem == 0
 18293                           || tem == pt_old
 18294                           || (tem - pt_old > 0 && tem < pos_after))
 18295                         {
 18296                           /* The glyphs from this string could have
 18297                              been reordered.  Find the one with the
 18298                              smallest string position.  Or there could
 18299                              be a character in the string with the
 18300                              `cursor' property, which means display
 18301                              cursor on that character's glyph.  */
 18302                           ptrdiff_t strpos = glyph->charpos;
 18303 
 18304                           if (tem)
 18305                             {
 18306                               cursor = glyph;
 18307                               string_from_text_prop = true;
 18308                             }
 18309                           for ( ;
 18310                                (row->reversed_p ? glyph > stop : glyph < stop)
 18311                                  && EQ (glyph->object, str);
 18312                                glyph += incr)
 18313                             {
 18314                               Lisp_Object cprop;
 18315                               ptrdiff_t gpos = glyph->charpos;
 18316 
 18317                               cprop = Fget_char_property (make_fixnum (gpos),
 18318                                                           Qcursor,
 18319                                                           glyph->object);
 18320                               if (!NILP (cprop))
 18321                                 {
 18322                                   cursor = glyph;
 18323                                   break;
 18324                                 }
 18325                               if (tem && glyph->charpos < strpos)
 18326                                 {
 18327                                   strpos = glyph->charpos;
 18328                                   cursor = glyph;
 18329                                 }
 18330                             }
 18331 
 18332                           if (tem == pt_old
 18333                               || (tem - pt_old > 0 && tem < pos_after))
 18334                             goto compute_x;
 18335                         }
 18336                       if (tem)
 18337                         pos = tem + 1; /* don't find previous instances */
 18338                     }
 18339                   /* This string is not what we want; skip all of the
 18340                      glyphs that came from it.  */
 18341                   while ((row->reversed_p ? glyph > stop : glyph < stop)
 18342                          && EQ (glyph->object, str))
 18343                     glyph += incr;
 18344                 }
 18345               else
 18346                 glyph += incr;
 18347             }
 18348 
 18349           /* If we reached the end of the line, and END was from a string,
 18350              the cursor is not on this line.  */
 18351           if (cursor == NULL
 18352               && (row->reversed_p ? glyph <= end : glyph >= end)
 18353               && (row->reversed_p ? end > glyphs_end : end < glyphs_end)
 18354               && STRINGP (end->object)
 18355               && row->continued_p)
 18356             return false;
 18357         }
 18358       /* A truncated row may not include PT among its character positions.
 18359          Setting the cursor inside the scroll margin will trigger
 18360          recalculation of hscroll in hscroll_window_tree.  But if a
 18361          display string covers point, defer to the string-handling
 18362          code below to figure this out.  */
 18363       else if (row->truncated_on_left_p && pt_old < bpos_min)
 18364         {
 18365           cursor = glyph_before;
 18366           x = -1;
 18367         }
 18368       else if ((row->truncated_on_right_p && pt_old > bpos_max)
 18369                /* Zero-width characters produce no glyphs.  */
 18370                || (!empty_line_p
 18371                    && (row->reversed_p
 18372                        ? glyph_after > glyphs_end
 18373                        : glyph_after < glyphs_end)))
 18374         {
 18375           cursor = glyph_after;
 18376           x = -1;
 18377         }
 18378     }
 18379 
 18380  compute_x:
 18381   if (cursor != NULL)
 18382     glyph = cursor;
 18383   else if (glyph == glyphs_end
 18384            && pos_before == pos_after
 18385            && STRINGP ((row->reversed_p
 18386                         ? row->glyphs[TEXT_AREA] + row->used[TEXT_AREA] - 1
 18387                         : row->glyphs[TEXT_AREA])->object))
 18388     {
 18389       /* If all the glyphs of this row came from strings, put the
 18390          cursor on the first glyph of the row.  This avoids having the
 18391          cursor outside of the text area in this very rare and hard
 18392          use case.  */
 18393       glyph =
 18394         row->reversed_p
 18395         ? row->glyphs[TEXT_AREA] + row->used[TEXT_AREA] - 1
 18396         : row->glyphs[TEXT_AREA];
 18397     }
 18398   if (x < 0)
 18399     {
 18400       struct glyph *g;
 18401 
 18402       /* Need to compute x that corresponds to GLYPH.  */
 18403       for (g = row->glyphs[TEXT_AREA], x = row->x; g < glyph; g++)
 18404         {
 18405           if (g >= row->glyphs[TEXT_AREA] + row->used[TEXT_AREA])
 18406             emacs_abort ();
 18407           x += g->pixel_width;
 18408         }
 18409     }
 18410 
 18411   /* ROW could be part of a continued line, which, under bidi
 18412      reordering, might have other rows whose start and end charpos
 18413      occlude point.  Only set w->cursor if we found a better
 18414      approximation to the cursor position than we have from previously
 18415      examined candidate rows belonging to the same continued line.  */
 18416   if (/* We already have a candidate row.  */
 18417       w->cursor.vpos >= 0
 18418       /* That candidate is not the row we are processing.  */
 18419       && MATRIX_ROW (matrix, w->cursor.vpos) != row
 18420       /* Make sure cursor.vpos specifies a row whose start and end
 18421          charpos occlude point, and it is valid candidate for being a
 18422          cursor-row.  This is because some callers of this function
 18423          leave cursor.vpos at the row where the cursor was displayed
 18424          during the last redisplay cycle.  */
 18425       && MATRIX_ROW_START_CHARPOS (MATRIX_ROW (matrix, w->cursor.vpos)) <= pt_old
 18426       && pt_old <= MATRIX_ROW_END_CHARPOS (MATRIX_ROW (matrix, w->cursor.vpos))
 18427       && cursor_row_p (MATRIX_ROW (matrix, w->cursor.vpos)))
 18428     {
 18429       struct glyph *g1
 18430         = MATRIX_ROW_GLYPH_START (matrix, w->cursor.vpos) + w->cursor.hpos;
 18431 
 18432       /* Don't consider glyphs that are outside TEXT_AREA.  */
 18433       if (!(row->reversed_p ? glyph > glyphs_end : glyph < glyphs_end))
 18434         return false;
 18435       /* Keep the candidate whose buffer position is the closest to
 18436          point or has the `cursor' property.  */
 18437       if (/* Previous candidate is a glyph in TEXT_AREA of that row.  */
 18438           w->cursor.hpos >= 0
 18439           && w->cursor.hpos < MATRIX_ROW_USED (matrix, w->cursor.vpos)
 18440           && ((BUFFERP (g1->object)
 18441                && (g1->charpos == pt_old /* An exact match always wins.  */
 18442                    || (BUFFERP (glyph->object)
 18443                        && eabs (g1->charpos - pt_old)
 18444                        < eabs (glyph->charpos - pt_old))))
 18445               /* Previous candidate is a glyph from a string that has
 18446                  a non-nil `cursor' property.  */
 18447               || (STRINGP (g1->object)
 18448                   && (!NILP (Fget_char_property (make_fixnum (g1->charpos),
 18449                                                 Qcursor, g1->object))
 18450                       /* Previous candidate is from the same display
 18451                          string as this one, and the display string
 18452                          came from a text property.  */
 18453                       || (EQ (g1->object, glyph->object)
 18454                           && string_from_text_prop)
 18455                       /* this candidate is from newline and its
 18456                          position is not an exact match */
 18457                       || (NILP (glyph->object)
 18458                           && glyph->charpos != pt_old)))))
 18459         return false;
 18460       /* If this candidate gives an exact match, use that.  */
 18461       if (!((BUFFERP (glyph->object) && glyph->charpos == pt_old)
 18462             /* If this candidate is a glyph created for the
 18463                terminating newline of a line, and point is on that
 18464                newline, it wins because it's an exact match.  */
 18465             || (!row->continued_p
 18466                 && NILP (glyph->object)
 18467                 && glyph->charpos == 0
 18468                 && pt_old == MATRIX_ROW_END_CHARPOS (row) - 1))
 18469           /* Otherwise, keep the candidate that comes from a row
 18470              spanning less buffer positions.  This may win when one or
 18471              both candidate positions are on glyphs that came from
 18472              display strings, for which we cannot compare buffer
 18473              positions.  */
 18474           && MATRIX_ROW_END_CHARPOS (MATRIX_ROW (matrix, w->cursor.vpos))
 18475              - MATRIX_ROW_START_CHARPOS (MATRIX_ROW (matrix, w->cursor.vpos))
 18476              < MATRIX_ROW_END_CHARPOS (row) - MATRIX_ROW_START_CHARPOS (row))
 18477         return false;
 18478     }
 18479   w->cursor.hpos = glyph - row->glyphs[TEXT_AREA];
 18480   w->cursor.x = x;
 18481   w->cursor.vpos = MATRIX_ROW_VPOS (row, matrix) + dvpos;
 18482   w->cursor.y = row->y + dy;
 18483 
 18484   if (w == XWINDOW (selected_window))
 18485     {
 18486       if (!row->continued_p
 18487           && !MATRIX_ROW_CONTINUATION_LINE_P (row)
 18488           && row->x == 0)
 18489         {
 18490           this_line_buffer = XBUFFER (w->contents);
 18491 
 18492           CHARPOS (this_line_start_pos)
 18493             = MATRIX_ROW_START_CHARPOS (row) + delta;
 18494           BYTEPOS (this_line_start_pos)
 18495             = MATRIX_ROW_START_BYTEPOS (row) + delta_bytes;
 18496 
 18497           CHARPOS (this_line_end_pos)
 18498             = Z - (MATRIX_ROW_END_CHARPOS (row) + delta);
 18499           BYTEPOS (this_line_end_pos)
 18500             = Z_BYTE - (MATRIX_ROW_END_BYTEPOS (row) + delta_bytes);
 18501 
 18502           this_line_y = w->cursor.y;
 18503           this_line_pixel_height = row->height;
 18504           this_line_vpos = w->cursor.vpos;
 18505           this_line_start_x = row->x;
 18506         }
 18507       else
 18508         CHARPOS (this_line_start_pos) = 0;
 18509     }
 18510 
 18511   return true;
 18512 }
 18513 
 18514 
 18515 /* Run window scroll functions, if any, for WINDOW with new window
 18516    start STARTP.  Sets the window start of WINDOW to that position.
 18517 
 18518    We assume that the window's buffer is really current.  */
 18519 
 18520 static struct text_pos
 18521 run_window_scroll_functions (Lisp_Object window, struct text_pos startp)
 18522 {
 18523   struct window *w = XWINDOW (window);
 18524   SET_MARKER_FROM_TEXT_POS (w->start, startp);
 18525 
 18526   eassert (current_buffer == XBUFFER (w->contents));
 18527 
 18528   if (!NILP (Vwindow_scroll_functions))
 18529     {
 18530       specpdl_ref count = SPECPDL_INDEX ();
 18531       specbind (Qinhibit_quit, Qt);
 18532       safe_run_hooks_2
 18533         (Qwindow_scroll_functions, window, make_fixnum (CHARPOS (startp)));
 18534       unbind_to (count, Qnil);
 18535       SET_TEXT_POS_FROM_MARKER (startp, w->start);
 18536       /* In case the hook functions switch buffers.  */
 18537       set_buffer_internal (XBUFFER (w->contents));
 18538     }
 18539 
 18540   return startp;
 18541 }
 18542 
 18543 
 18544 /* Make sure the line containing the cursor is fully visible.
 18545    A value of true means there is nothing to be done.
 18546    (Either the line is fully visible, or it cannot be made so,
 18547    or we cannot tell.)
 18548 
 18549    If FORCE_P, return false even if partial visible cursor row
 18550    is higher than window.
 18551 
 18552    If CURRENT_MATRIX_P, use the information from the
 18553    window's current glyph matrix; otherwise use the desired glyph
 18554    matrix.
 18555 
 18556    If JUST_TEST_USER_PREFERENCE_P, just test what the value of
 18557    make-cursor-row-fully-visible requires, don't test the actual
 18558    cursor position.  The assumption is that in that case the caller
 18559    performs the necessary testing of the cursor position.
 18560 
 18561    A value of false means the caller should do scrolling
 18562    as if point had gone off the screen.  */
 18563 
 18564 static bool
 18565 cursor_row_fully_visible_p (struct window *w, bool force_p,
 18566                             bool current_matrix_p,
 18567                             bool just_test_user_preference_p)
 18568 {
 18569   struct glyph_matrix *matrix;
 18570   struct glyph_row *row;
 18571   int window_height;
 18572   Lisp_Object mclfv_p =
 18573     buffer_local_value (Qmake_cursor_line_fully_visible, w->contents);
 18574 
 18575   /* If no local binding, use the global value.  */
 18576   if (BASE_EQ (mclfv_p, Qunbound))
 18577     mclfv_p = Vmake_cursor_line_fully_visible;
 18578   /* Follow mode sets the variable to a Lisp function in buffers that
 18579      are under Follow mode.  */
 18580   if (FUNCTIONP (mclfv_p))
 18581     {
 18582       Lisp_Object window;
 18583       XSETWINDOW (window, w);
 18584       /* Implementation note: if the function we call here signals an
 18585          error, we will NOT scroll when the cursor is partially-visible.  */
 18586       Lisp_Object val = safe_call1 (mclfv_p, window);
 18587       if (NILP (val))
 18588         return true;
 18589       else if (just_test_user_preference_p)
 18590         return false;
 18591     }
 18592   else if (NILP (mclfv_p))
 18593     return true;
 18594   else if (just_test_user_preference_p)
 18595     return false;
 18596 
 18597   /* It's not always possible to find the cursor, e.g, when a window
 18598      is full of overlay strings.  Don't do anything in that case.  */
 18599   if (w->cursor.vpos < 0)
 18600     return true;
 18601 
 18602   matrix = current_matrix_p ? w->current_matrix : w->desired_matrix;
 18603   row = MATRIX_ROW (matrix, w->cursor.vpos);
 18604 
 18605   /* If the cursor row is not partially visible, there's nothing to do.  */
 18606   if (!MATRIX_ROW_PARTIALLY_VISIBLE_P (w, row))
 18607     return true;
 18608 
 18609   /* If the row the cursor is in is taller than the window's height,
 18610      it's not clear what to do, so do nothing.  */
 18611   window_height = window_box_height (w);
 18612   if (row->height >= window_height)
 18613     {
 18614       if (!force_p || MINI_WINDOW_P (w)
 18615           || w->vscroll || w->cursor.vpos == 0)
 18616         return true;
 18617     }
 18618   return false;
 18619 }
 18620 
 18621 
 18622 /* Try scrolling PT into view in window WINDOW.  JUST_THIS_ONE_P
 18623    means only WINDOW is redisplayed in redisplay_internal.
 18624    TEMP_SCROLL_STEP has the same meaning as emacs_scroll_step, and is used
 18625    in redisplay_window to bring a partially visible line into view in
 18626    the case that only the cursor has moved.
 18627 
 18628    LAST_LINE_MISFIT should be true if we're scrolling because the
 18629    last screen line's vertical height extends past the end of the screen.
 18630 
 18631    Value is
 18632 
 18633    1    if scrolling succeeded
 18634 
 18635    0    if scrolling didn't find point.
 18636 
 18637    -1   if new fonts have been loaded so that we must interrupt
 18638    redisplay, adjust glyph matrices, and try again.  */
 18639 
 18640 enum
 18641 {
 18642   SCROLLING_SUCCESS = 1,
 18643   SCROLLING_FAILED = 0,
 18644   SCROLLING_NEED_LARGER_MATRICES = -1
 18645 };
 18646 
 18647 /* If scroll-conservatively is more than this, never recenter.
 18648 
 18649    If you change this, don't forget to update the doc string of
 18650    `scroll-conservatively' and the Emacs manual.  */
 18651 #define SCROLL_LIMIT 100
 18652 
 18653 static int
 18654 try_scrolling (Lisp_Object window, bool just_this_one_p,
 18655                intmax_t arg_scroll_conservatively, intmax_t scroll_step,
 18656                bool temp_scroll_step, bool last_line_misfit)
 18657 {
 18658   struct window *w = XWINDOW (window);
 18659   struct text_pos pos, startp;
 18660   struct it it;
 18661   int this_scroll_margin, scroll_max, rc, height;
 18662   int dy = 0, amount_to_scroll = 0;
 18663   bool scroll_down_p = false;
 18664   int extra_scroll_margin_lines = last_line_misfit;
 18665   Lisp_Object aggressive;
 18666   /* We will never try scrolling more than this number of lines.  */
 18667   int scroll_limit = SCROLL_LIMIT;
 18668   int frame_line_height = default_line_pixel_height (w);
 18669 
 18670 #ifdef GLYPH_DEBUG
 18671   debug_method_add (w, "try_scrolling");
 18672 #endif
 18673 
 18674   SET_TEXT_POS_FROM_MARKER (startp, w->start);
 18675 
 18676   this_scroll_margin = window_scroll_margin (w, MARGIN_IN_PIXELS);
 18677 
 18678   /* Force arg_scroll_conservatively to have a reasonable value, to
 18679      avoid scrolling too far away with slow move_it_* functions.  Note
 18680      that the user can supply scroll-conservatively equal to
 18681      `most-positive-fixnum', which can be larger than INT_MAX.  */
 18682   if (arg_scroll_conservatively > scroll_limit)
 18683     {
 18684       arg_scroll_conservatively = scroll_limit + 1;
 18685       scroll_max = scroll_limit * frame_line_height;
 18686     }
 18687   else if (0 < scroll_step || 0 < arg_scroll_conservatively || temp_scroll_step)
 18688     /* Compute how much we should try to scroll maximally to bring
 18689        point into view.  */
 18690     {
 18691       intmax_t scroll_lines_max
 18692         = max (scroll_step, max (arg_scroll_conservatively, temp_scroll_step));
 18693       int scroll_lines = clip_to_bounds (0, scroll_lines_max, 1000000);
 18694       scroll_max = scroll_lines * frame_line_height;
 18695     }
 18696   else if (NUMBERP (BVAR (current_buffer, scroll_down_aggressively))
 18697            || NUMBERP (BVAR (current_buffer, scroll_up_aggressively)))
 18698     /* We're trying to scroll because of aggressive scrolling but no
 18699        scroll_step is set.  Choose an arbitrary one.  */
 18700     scroll_max = 10 * frame_line_height;
 18701   else
 18702     scroll_max = 0;
 18703 
 18704  too_near_end:
 18705 
 18706   /* Decide whether to scroll down.  */
 18707   if (PT > CHARPOS (startp))
 18708     {
 18709       int scroll_margin_y;
 18710 
 18711       /* Compute the pixel ypos of the scroll margin, then move IT to
 18712          either that ypos or PT, whichever comes first.  */
 18713       start_display (&it, w, startp);
 18714       scroll_margin_y = it.last_visible_y - partial_line_height (&it)
 18715         - this_scroll_margin
 18716         - frame_line_height * extra_scroll_margin_lines;
 18717       move_it_to (&it, PT, -1, scroll_margin_y - 1, -1,
 18718                   (MOVE_TO_POS | MOVE_TO_Y));
 18719 
 18720       if (PT > CHARPOS (it.current.pos))
 18721         {
 18722           int y0 = line_bottom_y (&it);
 18723           /* Compute how many pixels below window bottom to stop searching
 18724              for PT.  This avoids costly search for PT that is far away if
 18725              the user limited scrolling by a small number of lines, but
 18726              always finds PT if scroll_conservatively is set to a large
 18727              number, such as most-positive-fixnum.  */
 18728           int slack = max (scroll_max, 10 * frame_line_height);
 18729           int y_to_move = it.last_visible_y + slack;
 18730 
 18731           /* Compute the distance from the scroll margin to PT or to
 18732              the scroll limit, whichever comes first.  This should
 18733              include the height of the cursor line, to make that line
 18734              fully visible.  */
 18735           move_it_to (&it, PT, -1, y_to_move,
 18736                       -1, MOVE_TO_POS | MOVE_TO_Y);
 18737           dy = line_bottom_y (&it) - y0;
 18738 
 18739           if (dy > scroll_max)
 18740             return SCROLLING_FAILED;
 18741 
 18742           if (dy > 0)
 18743             scroll_down_p = true;
 18744         }
 18745       else if (PT == IT_CHARPOS (it)
 18746                && IT_CHARPOS (it) < ZV
 18747                && it.method == GET_FROM_STRING
 18748                && arg_scroll_conservatively > scroll_limit
 18749                && it.current_x == 0)
 18750         {
 18751           enum move_it_result skip;
 18752           int y1 = it.current_y;
 18753           int vpos;
 18754 
 18755           /* A before-string that includes newlines and is displayed
 18756              on the last visible screen line could fail us under
 18757              scroll-conservatively > 100, because we will be unable to
 18758              position the cursor on that last visible line.  Try to
 18759              recover by finding the first screen line that has some
 18760              glyphs coming from the buffer text.  */
 18761           do {
 18762             skip = move_it_in_display_line_to (&it, ZV, -1, MOVE_TO_POS);
 18763             if (skip != MOVE_NEWLINE_OR_CR
 18764                 || IT_CHARPOS (it) != PT
 18765                 || it.method == GET_FROM_BUFFER)
 18766               break;
 18767             vpos = it.vpos;
 18768             move_it_to (&it, -1, -1, -1, vpos + 1, MOVE_TO_VPOS);
 18769           } while (it.vpos > vpos);
 18770 
 18771           dy = it.current_y - y1;
 18772 
 18773           if (dy > scroll_max)
 18774             return SCROLLING_FAILED;
 18775 
 18776           if (dy > 0)
 18777             scroll_down_p = true;
 18778         }
 18779     }
 18780 
 18781   if (scroll_down_p)
 18782     {
 18783       /* Point is in or below the bottom scroll margin, so move the
 18784          window start down.  If scrolling conservatively, move it just
 18785          enough down to make point visible.  If scroll_step is set,
 18786          move it down by scroll_step.  */
 18787       if (arg_scroll_conservatively)
 18788         amount_to_scroll
 18789           = min (max (dy, frame_line_height),
 18790                  frame_line_height * arg_scroll_conservatively);
 18791       else if (scroll_step || temp_scroll_step)
 18792         amount_to_scroll = scroll_max;
 18793       else
 18794         {
 18795           aggressive = BVAR (current_buffer, scroll_up_aggressively);
 18796           height = WINDOW_BOX_TEXT_HEIGHT (w);
 18797           if (NUMBERP (aggressive))
 18798             {
 18799               double float_amount = XFLOATINT (aggressive) * height;
 18800               int aggressive_scroll = float_amount;
 18801               if (aggressive_scroll == 0 && float_amount > 0)
 18802                 aggressive_scroll = 1;
 18803               /* Don't let point enter the scroll margin near top of
 18804                  the window.  This could happen if the value of
 18805                  scroll_up_aggressively is too large and there are
 18806                  non-zero margins, because scroll_up_aggressively
 18807                  means put point that fraction of window height
 18808                  _from_the_bottom_margin_.  */
 18809               if (aggressive_scroll + 2 * this_scroll_margin > height)
 18810                 aggressive_scroll = height - 2 * this_scroll_margin;
 18811               amount_to_scroll = dy + aggressive_scroll;
 18812             }
 18813         }
 18814 
 18815       if (amount_to_scroll <= 0)
 18816         return SCROLLING_FAILED;
 18817 
 18818       start_display (&it, w, startp);
 18819       if (arg_scroll_conservatively <= scroll_limit)
 18820         move_it_vertically (&it, amount_to_scroll);
 18821       else
 18822         {
 18823           /* Extra precision for users who set scroll-conservatively
 18824              to a large number: make sure the amount we scroll
 18825              the window start is never less than amount_to_scroll,
 18826              which was computed as distance from window bottom to
 18827              point.  This matters when lines at window top and lines
 18828              below window bottom have different height.  */
 18829           struct it it1;
 18830           void *it1data = NULL;
 18831           /* We use a temporary it1 because line_bottom_y can modify
 18832              its argument, if it moves one line down; see there.  */
 18833           int start_y;
 18834 
 18835           SAVE_IT (it1, it, it1data);
 18836           start_y = line_bottom_y (&it1);
 18837           do {
 18838             RESTORE_IT (&it, &it, it1data);
 18839             move_it_by_lines (&it, 1);
 18840             SAVE_IT (it1, it, it1data);
 18841           } while (IT_CHARPOS (it) < ZV
 18842                    && line_bottom_y (&it1) - start_y < amount_to_scroll);
 18843           bidi_unshelve_cache (it1data, true);
 18844         }
 18845 
 18846       /* If STARTP is unchanged, move it down another screen line.  */
 18847       if (IT_CHARPOS (it) == CHARPOS (startp))
 18848         move_it_by_lines (&it, 1);
 18849       startp = it.current.pos;
 18850     }
 18851   else
 18852     {
 18853       struct text_pos scroll_margin_pos = startp;
 18854       int y_offset = 0;
 18855 
 18856       /* See if point is inside the scroll margin at the top of the
 18857          window.  */
 18858       if (this_scroll_margin)
 18859         {
 18860           int y_start;
 18861 
 18862           start_display (&it, w, startp);
 18863           y_start = it.current_y;
 18864           move_it_vertically (&it, this_scroll_margin);
 18865           scroll_margin_pos = it.current.pos;
 18866           /* If we didn't move enough before hitting ZV, request
 18867              additional amount of scroll, to move point out of the
 18868              scroll margin.  */
 18869           if (IT_CHARPOS (it) == ZV
 18870               && it.current_y - y_start < this_scroll_margin)
 18871             y_offset = this_scroll_margin - (it.current_y - y_start);
 18872         }
 18873 
 18874       if (PT < CHARPOS (scroll_margin_pos))
 18875         {
 18876           /* Point is in the scroll margin at the top of the window or
 18877              above what is displayed in the window.  */
 18878           int y0, y_to_move;
 18879 
 18880           /* Compute the vertical distance from PT to the scroll
 18881              margin position.  Move as far as scroll_max allows, or
 18882              one screenful, or 10 screen lines, whichever is largest.
 18883              Give up if distance is greater than scroll_max or if we
 18884              didn't reach the scroll margin position.  */
 18885           SET_TEXT_POS (pos, PT, PT_BYTE);
 18886           start_display (&it, w, pos);
 18887           y0 = it.current_y;
 18888           y_to_move = max (it.last_visible_y,
 18889                            max (scroll_max, 10 * frame_line_height));
 18890           move_it_to (&it, CHARPOS (scroll_margin_pos), 0,
 18891                       y_to_move, -1,
 18892                       MOVE_TO_POS | MOVE_TO_X | MOVE_TO_Y);
 18893           dy = it.current_y - y0;
 18894           if (dy > scroll_max
 18895               || IT_CHARPOS (it) < CHARPOS (scroll_margin_pos))
 18896             return SCROLLING_FAILED;
 18897 
 18898           /* Additional scroll for when ZV was too close to point.  */
 18899           dy += y_offset;
 18900 
 18901           /* Compute new window start.  */
 18902           start_display (&it, w, startp);
 18903 
 18904           if (arg_scroll_conservatively)
 18905             amount_to_scroll
 18906               = min (max (dy, frame_line_height),
 18907                      frame_line_height * arg_scroll_conservatively);
 18908           else if (scroll_step || temp_scroll_step)
 18909             amount_to_scroll = scroll_max;
 18910           else
 18911             {
 18912               aggressive = BVAR (current_buffer, scroll_down_aggressively);
 18913               height = WINDOW_BOX_TEXT_HEIGHT (w);
 18914               if (NUMBERP (aggressive))
 18915                 {
 18916                   double float_amount = XFLOATINT (aggressive) * height;
 18917                   int aggressive_scroll = float_amount;
 18918                   if (aggressive_scroll == 0 && float_amount > 0)
 18919                     aggressive_scroll = 1;
 18920                   /* Don't let point enter the scroll margin near
 18921                      bottom of the window, if the value of
 18922                      scroll_down_aggressively happens to be too
 18923                      large.  */
 18924                   if (aggressive_scroll + 2 * this_scroll_margin > height)
 18925                     aggressive_scroll = height - 2 * this_scroll_margin;
 18926                   amount_to_scroll = dy + aggressive_scroll;
 18927                 }
 18928             }
 18929 
 18930           if (amount_to_scroll <= 0)
 18931             return SCROLLING_FAILED;
 18932 
 18933           move_it_vertically_backward (&it, amount_to_scroll);
 18934           startp = it.current.pos;
 18935         }
 18936     }
 18937 
 18938   /* Run window scroll functions.  */
 18939   startp = run_window_scroll_functions (window, startp);
 18940 
 18941   /* Display the window.  Give up if new fonts are loaded, or if point
 18942      doesn't appear.  */
 18943   if (!try_window (window, startp, 0))
 18944     rc = SCROLLING_NEED_LARGER_MATRICES;
 18945   else if (w->cursor.vpos < 0)
 18946     {
 18947       clear_glyph_matrix (w->desired_matrix);
 18948       rc = SCROLLING_FAILED;
 18949     }
 18950   else
 18951     {
 18952       /* Maybe forget recorded base line for line number display.  */
 18953       if (!just_this_one_p
 18954           || current_buffer->clip_changed
 18955           || BEG_UNCHANGED < CHARPOS (startp))
 18956         w->base_line_number = 0;
 18957 
 18958       /* If cursor ends up on a partially visible line,
 18959          treat that as being off the bottom of the screen.  */
 18960       if (! cursor_row_fully_visible_p (w, extra_scroll_margin_lines <= 1,
 18961                                         false, false)
 18962           /* It's possible that the cursor is on the first line of the
 18963              buffer, which is partially obscured due to a vscroll
 18964              (Bug#7537).  In that case, avoid looping forever. */
 18965           && extra_scroll_margin_lines < w->desired_matrix->nrows - 1)
 18966         {
 18967           clear_glyph_matrix (w->desired_matrix);
 18968           ++extra_scroll_margin_lines;
 18969           goto too_near_end;
 18970         }
 18971       rc = SCROLLING_SUCCESS;
 18972     }
 18973 
 18974   return rc;
 18975 }
 18976 
 18977 
 18978 /* Compute a suitable window start for window W if display of W starts
 18979    on a continuation line.  Value is true if a new window start
 18980    was computed.
 18981 
 18982    The new window start will be computed, based on W's width, starting
 18983    from the start of the continued line.  It is the start of the
 18984    screen line with the minimum distance from the old start W->start,
 18985    which is still before point (otherwise point will definitely not
 18986    be visible in the window).  */
 18987 
 18988 static bool
 18989 compute_window_start_on_continuation_line (struct window *w)
 18990 {
 18991   struct text_pos pos, start_pos, pos_before_pt;
 18992   bool window_start_changed_p = false;
 18993 
 18994   SET_TEXT_POS_FROM_MARKER (start_pos, w->start);
 18995 
 18996   /* If window start is on a continuation line...  Window start may be
 18997      < BEGV in case there's invisible text at the start of the
 18998      buffer (M-x rmail, for example).  */
 18999   if (CHARPOS (start_pos) > BEGV
 19000       && FETCH_BYTE (BYTEPOS (start_pos) - 1) != '\n')
 19001     {
 19002       struct it it;
 19003       struct glyph_row *row;
 19004 
 19005       /* Handle the case that the window start is out of range.  */
 19006       if (CHARPOS (start_pos) < BEGV)
 19007         SET_TEXT_POS (start_pos, BEGV, BEGV_BYTE);
 19008       else if (CHARPOS (start_pos) > ZV)
 19009         SET_TEXT_POS (start_pos, ZV, ZV_BYTE);
 19010 
 19011       /* Find the start of the continued line.  This should be fast
 19012          because find_newline is fast (newline cache).  */
 19013       row = w->desired_matrix->rows + window_wants_tab_line (w)
 19014                                     + window_wants_header_line (w);
 19015       init_iterator (&it, w, CHARPOS (start_pos), BYTEPOS (start_pos),
 19016                      row, DEFAULT_FACE_ID);
 19017       reseat_at_previous_visible_line_start (&it);
 19018 
 19019       /* Give up (by not using the code in the block below) and say it
 19020          takes too much time to compute a new window start, if the
 19021          line start is "too far" away from the window start.  Also,
 19022          give up if the line start is after point, as in that case
 19023          point will not be visible with any window start we
 19024          compute.  */
 19025       if (IT_CHARPOS (it) <= PT
 19026           && (CHARPOS (start_pos) - IT_CHARPOS (it)
 19027               /* PXW: Do we need upper bounds here?  */
 19028               < WINDOW_TOTAL_LINES (w) * WINDOW_TOTAL_COLS (w)))
 19029         {
 19030           int min_distance, distance;
 19031 
 19032           /* Move forward by display lines to find the new window
 19033              start.  If window width was enlarged, the new start can
 19034              be expected to be > the old start.  If window width was
 19035              decreased, the new window start will be < the old start.
 19036              So, we're looking for the display line start with the
 19037              minimum distance from the old window start.  */
 19038           pos_before_pt = pos = it.current.pos;
 19039           min_distance = DISP_INFINITY;
 19040           while ((distance = eabs (CHARPOS (start_pos) - IT_CHARPOS (it))),
 19041                  distance < min_distance)
 19042             {
 19043               min_distance = distance;
 19044               if (CHARPOS (pos) <= PT)
 19045                 pos_before_pt = pos;
 19046               pos = it.current.pos;
 19047               if (it.line_wrap == WORD_WRAP)
 19048                 {
 19049                   /* Under WORD_WRAP, move_it_by_lines is likely to
 19050                      overshoot and stop not at the first, but the
 19051                      second character from the left margin.  So in
 19052                      that case, we need a more tight control on the X
 19053                      coordinate of the iterator than move_it_by_lines
 19054                      promises in its contract.  The method is to first
 19055                      go to the last (rightmost) visible character of a
 19056                      line, then move to the leftmost character on the
 19057                      next line in a separate call.  */
 19058                   move_it_to (&it, ZV, it.last_visible_x, it.current_y, -1,
 19059                               MOVE_TO_POS | MOVE_TO_X | MOVE_TO_Y);
 19060                   move_it_to (&it, ZV, 0,
 19061                               it.current_y + it.max_ascent + it.max_descent, -1,
 19062                               MOVE_TO_POS | MOVE_TO_X | MOVE_TO_Y);
 19063                 }
 19064               else
 19065                 move_it_by_lines (&it, 1);
 19066             }
 19067 
 19068           /* It makes very little sense to make the new window start
 19069              after point, as point won't be visible.  If that's what
 19070              the loop above finds, fall back on the candidate before
 19071              or at point that is closest to the old window start.  */
 19072           if (CHARPOS (pos) > PT)
 19073             pos = pos_before_pt;
 19074 
 19075           /* Set the window start there.  */
 19076           SET_MARKER_FROM_TEXT_POS (w->start, pos);
 19077           window_start_changed_p = true;
 19078         }
 19079     }
 19080 
 19081   return window_start_changed_p;
 19082 }
 19083 
 19084 
 19085 /* Try cursor movement in case text has not changed in window WINDOW,
 19086    with window start STARTP.  Value is
 19087 
 19088    CURSOR_MOVEMENT_SUCCESS if successful
 19089 
 19090    CURSOR_MOVEMENT_CANNOT_BE_USED if this method cannot be used
 19091 
 19092    CURSOR_MOVEMENT_MUST_SCROLL if we know we have to scroll the
 19093    display.  *SCROLL_STEP is set to true, under certain circumstances, if
 19094    we want to scroll as if scroll-step were set to 1.  See the code.
 19095 
 19096    CURSOR_MOVEMENT_NEED_LARGER_MATRICES if we need larger matrices, in
 19097    which case we have to abort this redisplay, and adjust matrices
 19098    first.  */
 19099 
 19100 enum
 19101 {
 19102   CURSOR_MOVEMENT_SUCCESS,
 19103   CURSOR_MOVEMENT_CANNOT_BE_USED,
 19104   CURSOR_MOVEMENT_MUST_SCROLL,
 19105   CURSOR_MOVEMENT_NEED_LARGER_MATRICES
 19106 };
 19107 
 19108 static int
 19109 try_cursor_movement (Lisp_Object window, struct text_pos startp,
 19110                      bool *scroll_step)
 19111 {
 19112   struct window *w = XWINDOW (window);
 19113   struct frame *f = XFRAME (w->frame);
 19114   int rc = CURSOR_MOVEMENT_CANNOT_BE_USED;
 19115 
 19116 #ifdef GLYPH_DEBUG
 19117   if (inhibit_try_cursor_movement)
 19118     return rc;
 19119 #endif
 19120 
 19121   /* Previously, there was a check for Lisp integer in the
 19122      if-statement below. Now, this field is converted to
 19123      ptrdiff_t, thus zero means invalid position in a buffer.  */
 19124   eassert (w->last_point > 0);
 19125   /* Likewise there was a check whether window_end_vpos is nil or larger
 19126      than the window.  Now window_end_vpos is int and so never nil, but
 19127      let's leave eassert to check whether it fits in the window.  */
 19128   eassert (!w->window_end_valid
 19129            || w->window_end_vpos < w->current_matrix->nrows);
 19130 
 19131   /* Handle case where text has not changed, only point, and it has
 19132      not moved off the frame.  */
 19133   if (/* Point may be in this window.  */
 19134       PT >= CHARPOS (startp)
 19135       /* Selective display hasn't changed.  */
 19136       && !current_buffer->clip_changed
 19137       /* Function force-mode-line-update is used to force a thorough
 19138          redisplay.  It sets either windows_or_buffers_changed or
 19139          update_mode_lines.  So don't take a shortcut here for these
 19140          cases.  */
 19141       && !update_mode_lines
 19142       && !windows_or_buffers_changed
 19143       && !f->cursor_type_changed
 19144       && NILP (Vshow_trailing_whitespace)
 19145       /* When display-line-numbers is in relative mode, moving point
 19146          requires to redraw the entire window.  */
 19147       && !EQ (Vdisplay_line_numbers, Qrelative)
 19148       && !EQ (Vdisplay_line_numbers, Qvisual)
 19149       /* When the current line number should be displayed in a
 19150          distinct face, moving point cannot be handled in optimized
 19151          way as below.  */
 19152       && !(!NILP (Vdisplay_line_numbers)
 19153            && NILP (Finternal_lisp_face_equal_p (Qline_number,
 19154                                                  Qline_number_current_line,
 19155                                                  w->frame)))
 19156       /* This code is not used for mini-buffer for the sake of the case
 19157          of redisplaying to replace an echo area message; since in
 19158          that case the mini-buffer contents per se are usually
 19159          unchanged.  This code is of no real use in the mini-buffer
 19160          since the handling of this_line_start_pos, etc., in redisplay
 19161          handles the same cases.  */
 19162       && !EQ (window, minibuf_window)
 19163       /* When overlay arrow is shown in current buffer, point movement
 19164          is no longer "simple", as it typically causes the overlay
 19165          arrow to move as well.  */
 19166       && !overlay_arrow_in_current_buffer_p ())
 19167     {
 19168       int this_scroll_margin, top_scroll_margin;
 19169       struct glyph_row *row = NULL;
 19170 
 19171 #ifdef GLYPH_DEBUG
 19172       debug_method_add (w, "cursor movement");
 19173 #endif
 19174 
 19175       this_scroll_margin = window_scroll_margin (w, MARGIN_IN_PIXELS);
 19176 
 19177       top_scroll_margin = this_scroll_margin;
 19178       if (window_wants_tab_line (w))
 19179         top_scroll_margin += CURRENT_TAB_LINE_HEIGHT (w);
 19180       if (window_wants_header_line (w))
 19181         top_scroll_margin += CURRENT_HEADER_LINE_HEIGHT (w);
 19182 
 19183       /* Start with the row the cursor was displayed during the last
 19184          not paused redisplay.  Give up if that row is not valid.  */
 19185       if (w->last_cursor_vpos < 0
 19186           || w->last_cursor_vpos >= w->current_matrix->nrows)
 19187         rc = CURSOR_MOVEMENT_MUST_SCROLL;
 19188       else
 19189         {
 19190           row = MATRIX_ROW (w->current_matrix, w->last_cursor_vpos);
 19191           /* Skip the tab-line and header-line rows, if any.  */
 19192           if (row->tab_line_p)
 19193             ++row;
 19194           if (row->mode_line_p)
 19195             ++row;
 19196           if (!row->enabled_p)
 19197             rc = CURSOR_MOVEMENT_MUST_SCROLL;
 19198         }
 19199 
 19200       if (rc == CURSOR_MOVEMENT_CANNOT_BE_USED)
 19201         {
 19202           bool scroll_p = false, must_scroll = false;
 19203           int last_y = window_text_bottom_y (w) - this_scroll_margin;
 19204 
 19205           if (PT > w->last_point)
 19206             {
 19207               /* Point has moved forward.  */
 19208               while (MATRIX_ROW_END_CHARPOS (row) < PT
 19209                      && MATRIX_ROW_BOTTOM_Y (row) < last_y)
 19210                 {
 19211                   eassert (row->enabled_p);
 19212                   ++row;
 19213                 }
 19214 
 19215               /* If the end position of a row equals the start
 19216                  position of the next row, and PT is at that position,
 19217                  we would rather display cursor in the next line.  */
 19218               while (MATRIX_ROW_BOTTOM_Y (row) < last_y
 19219                      && MATRIX_ROW_END_CHARPOS (row) == PT
 19220                      && row < MATRIX_MODE_LINE_ROW (w->current_matrix)
 19221                      && MATRIX_ROW_START_CHARPOS (row+1) >= PT
 19222                      && !cursor_row_p (row))
 19223                 ++row;
 19224 
 19225               /* If within the scroll margin, scroll.  Note that
 19226                  MATRIX_ROW_BOTTOM_Y gives the pixel position at which
 19227                  the next line would be drawn, and that
 19228                  this_scroll_margin can be zero.  */
 19229               if (MATRIX_ROW_BOTTOM_Y (row) > last_y
 19230                   || PT > MATRIX_ROW_END_CHARPOS (row)
 19231                   /* Line is completely visible last line in window
 19232                      and PT is to be set in the next line.  */
 19233                   || (MATRIX_ROW_BOTTOM_Y (row) == last_y
 19234                       && PT == MATRIX_ROW_END_CHARPOS (row)
 19235                       && !row->ends_at_zv_p
 19236                       && !MATRIX_ROW_ENDS_IN_MIDDLE_OF_CHAR_P (row)))
 19237                 scroll_p = true;
 19238             }
 19239           else if (PT < w->last_point)
 19240             {
 19241               /* Cursor has to be moved backward.  Note that PT >=
 19242                  CHARPOS (startp) because of the outer if-statement.  */
 19243               struct glyph_row *row0 = row;
 19244 
 19245               while (!row->mode_line_p
 19246                      && (MATRIX_ROW_START_CHARPOS (row) > PT
 19247                          || (MATRIX_ROW_START_CHARPOS (row) == PT
 19248                              && (MATRIX_ROW_STARTS_IN_MIDDLE_OF_CHAR_P (row)
 19249                                  || (/* STARTS_IN_MIDDLE_OF_STRING_P (row) */
 19250                                      row > w->current_matrix->rows
 19251                                      && (row-1)->ends_in_newline_from_string_p))))
 19252                      && (row->y > top_scroll_margin
 19253                          || CHARPOS (startp) == BEGV))
 19254                 {
 19255                   eassert (row->enabled_p);
 19256                   --row;
 19257                 }
 19258 
 19259               /* With bidi-reordered rows we can have buffer positions
 19260                  _decrease_ when going down by rows.  If we haven't
 19261                  found our row in the loop above, give it another try
 19262                  now going in the other direction from the original row.  */
 19263               if (!(MATRIX_ROW_START_CHARPOS (row) <= PT
 19264                     && PT <= MATRIX_ROW_END_CHARPOS (row))
 19265                   && row0->continued_p)
 19266                 {
 19267                   row = row0;
 19268                   while (MATRIX_ROW_START_CHARPOS (row) > PT
 19269                          && MATRIX_ROW_BOTTOM_Y (row) < last_y)
 19270                     {
 19271                       eassert (row->enabled_p);
 19272                       ++row;
 19273                     }
 19274                 }
 19275 
 19276               /* Consider the following case: Window starts at BEGV,
 19277                  there is invisible, intangible text at BEGV, so that
 19278                  display starts at some point START > BEGV.  It can
 19279                  happen that we are called with PT somewhere between
 19280                  BEGV and START.  Try to handle that case.  */
 19281               if (row < w->current_matrix->rows
 19282                   || row->mode_line_p)
 19283                 {
 19284                   row = w->current_matrix->rows;
 19285                   /* Skip the tab-line and header-line rows, if any.  */
 19286                   if (row->tab_line_p)
 19287                     ++row;
 19288                   if (row->mode_line_p)
 19289                     ++row;
 19290                 }
 19291 
 19292               /* Due to newlines in overlay strings, we may have to
 19293                  skip forward over overlay strings.  */
 19294               while (MATRIX_ROW_BOTTOM_Y (row) < last_y
 19295                      && MATRIX_ROW_END_CHARPOS (row) == PT
 19296                      && !cursor_row_p (row))
 19297                 ++row;
 19298 
 19299               /* If within the scroll margin, either the top one or
 19300                  the bottom one, scroll.  */
 19301               if ((row->y < top_scroll_margin
 19302                    && CHARPOS (startp) != BEGV)
 19303                   || MATRIX_ROW_BOTTOM_Y (row) > last_y
 19304                   || PT > MATRIX_ROW_END_CHARPOS (row)
 19305                   || (MATRIX_ROW_BOTTOM_Y (row) == last_y
 19306                       && PT == MATRIX_ROW_END_CHARPOS (row)
 19307                       && !row->ends_at_zv_p
 19308                       && !MATRIX_ROW_ENDS_IN_MIDDLE_OF_CHAR_P (row)))
 19309                 scroll_p = true;
 19310             }
 19311           else
 19312             {
 19313               /* Cursor did not move.  So don't scroll even if cursor line
 19314                  is partially visible, as it was so before.  */
 19315                  rc = CURSOR_MOVEMENT_SUCCESS;
 19316             }
 19317 
 19318           if ((PT < MATRIX_ROW_START_CHARPOS (row)
 19319                && (row == MATRIX_FIRST_TEXT_ROW (w->current_matrix)
 19320                    /* Don't give up if point is inside invisible text
 19321                       at the beginning of its glyph row.  */
 19322                    || (MATRIX_ROW_END_CHARPOS (row-1)
 19323                        == MATRIX_ROW_START_CHARPOS (row))))
 19324               || PT > MATRIX_ROW_END_CHARPOS (row))
 19325             {
 19326               /* if PT is not in the glyph row, give up.  */
 19327               rc = CURSOR_MOVEMENT_MUST_SCROLL;
 19328               must_scroll = true;
 19329             }
 19330           else if (rc != CURSOR_MOVEMENT_SUCCESS
 19331                    && !NILP (BVAR (XBUFFER (w->contents), bidi_display_reordering)))
 19332             {
 19333               struct glyph_row *row1;
 19334 
 19335               /* If rows are bidi-reordered and point moved, back up
 19336                  until we find a row that does not belong to a
 19337                  continuation line.  This is because we must consider
 19338                  all rows of a continued line as candidates for the
 19339                  new cursor positioning, since row start and end
 19340                  positions change non-linearly with vertical position
 19341                  in such rows.  */
 19342               /* FIXME: Revisit this when glyph ``spilling'' in
 19343                  continuation lines' rows is implemented for
 19344                  bidi-reordered rows.  */
 19345               for (row1 = MATRIX_FIRST_TEXT_ROW (w->current_matrix);
 19346                    MATRIX_ROW_CONTINUATION_LINE_P (row);
 19347                    --row)
 19348                 {
 19349                   /* If we hit the beginning of the displayed portion
 19350                      without finding the first row of a continued
 19351                      line, give up.  */
 19352                   if (row <= row1)
 19353                     {
 19354                       rc = CURSOR_MOVEMENT_MUST_SCROLL;
 19355                       break;
 19356                     }
 19357                   eassert (row->enabled_p);
 19358                 }
 19359             }
 19360           if (must_scroll)
 19361             ;
 19362           else if (rc != CURSOR_MOVEMENT_SUCCESS
 19363               && MATRIX_ROW_PARTIALLY_VISIBLE_P (w, row)
 19364               /* Make sure this isn't a header line nor a tab-line by
 19365                  any chance, since then MATRIX_ROW_PARTIALLY_VISIBLE_P
 19366                  might yield true.  */
 19367               && !row->mode_line_p
 19368               && !cursor_row_fully_visible_p (w, true, true, true))
 19369             {
 19370               if (PT == MATRIX_ROW_END_CHARPOS (row)
 19371                   && !row->ends_at_zv_p
 19372                   && !MATRIX_ROW_ENDS_IN_MIDDLE_OF_CHAR_P (row))
 19373                 rc = CURSOR_MOVEMENT_MUST_SCROLL;
 19374               else if (row->height > window_box_height (w))
 19375                 {
 19376                   /* If we end up in a partially visible line, let's
 19377                      make it fully visible, except when it's taller
 19378                      than the window, in which case we can't do much
 19379                      about it.  */
 19380                   *scroll_step = true;
 19381                   rc = CURSOR_MOVEMENT_MUST_SCROLL;
 19382                 }
 19383               else
 19384                 {
 19385                   set_cursor_from_row (w, row, w->current_matrix, 0, 0, 0, 0);
 19386                   if (!cursor_row_fully_visible_p (w, false, true, false))
 19387                     rc = CURSOR_MOVEMENT_MUST_SCROLL;
 19388                   else
 19389                     rc = CURSOR_MOVEMENT_SUCCESS;
 19390                 }
 19391             }
 19392           else if (scroll_p)
 19393             rc = CURSOR_MOVEMENT_MUST_SCROLL;
 19394           else if (rc != CURSOR_MOVEMENT_SUCCESS
 19395                    && !NILP (BVAR (XBUFFER (w->contents), bidi_display_reordering)))
 19396             {
 19397               /* With bidi-reordered rows, there could be more than
 19398                  one candidate row whose start and end positions
 19399                  occlude point.  We need to let set_cursor_from_row
 19400                  find the best candidate.  */
 19401               /* FIXME: Revisit this when glyph ``spilling'' in
 19402                  continuation lines' rows is implemented for
 19403                  bidi-reordered rows.  */
 19404               bool rv = false;
 19405               bool pt_invis = false;
 19406               Lisp_Object val = get_char_property_and_overlay (make_fixnum (PT),
 19407                                                                Qinvisible,
 19408                                                                Qnil, NULL);
 19409 
 19410               if (TEXT_PROP_MEANS_INVISIBLE (val) != 0)
 19411                 pt_invis = true;
 19412 
 19413               do
 19414                 {
 19415                   bool at_zv_p = false, exact_match_p = false;
 19416 
 19417                   /* If point is in invisible text, we cannot assume
 19418                      it must be after row's start position, since the
 19419                      row could have invisible text at its beginning
 19420                      where point is located.  */
 19421                   if ((pt_invis || MATRIX_ROW_START_CHARPOS (row) <= PT)
 19422                       && PT <= MATRIX_ROW_END_CHARPOS (row)
 19423                       && cursor_row_p (row))
 19424                     rv |= set_cursor_from_row (w, row, w->current_matrix,
 19425                                                0, 0, 0, 0);
 19426                   /* As soon as we've found the exact match for point,
 19427                      or the first suitable row whose ends_at_zv_p flag
 19428                      is set, we are done.  */
 19429                   if (rv)
 19430                     {
 19431                       at_zv_p = MATRIX_ROW (w->current_matrix,
 19432                                             w->cursor.vpos)->ends_at_zv_p;
 19433                       if (!at_zv_p
 19434                           && w->cursor.hpos >= 0
 19435                           && w->cursor.hpos < MATRIX_ROW_USED (w->current_matrix,
 19436                                                                w->cursor.vpos))
 19437                         {
 19438                           struct glyph_row *candidate =
 19439                             MATRIX_ROW (w->current_matrix, w->cursor.vpos);
 19440                           struct glyph *g =
 19441                             candidate->glyphs[TEXT_AREA] + w->cursor.hpos;
 19442                           ptrdiff_t endpos = MATRIX_ROW_END_CHARPOS (candidate);
 19443 
 19444                           exact_match_p =
 19445                             (BUFFERP (g->object) && g->charpos == PT)
 19446                             || (NILP (g->object)
 19447                                 && (g->charpos == PT
 19448                                     || (g->charpos == 0 && endpos - 1 == PT)));
 19449                           /* Perhaps the point position is inside
 19450                              invisible text?  In that case, we trust
 19451                              'set_cursor_from_row' to do its job and
 19452                              find the best position for the cursor.  */
 19453                           if (!exact_match_p && pt_invis)
 19454                             exact_match_p = true;
 19455                         }
 19456                       if (at_zv_p || exact_match_p)
 19457                         {
 19458                           rc = CURSOR_MOVEMENT_SUCCESS;
 19459                           break;
 19460                         }
 19461                     }
 19462                   if (MATRIX_ROW_BOTTOM_Y (row) == last_y)
 19463                     break;
 19464                   ++row;
 19465                 }
 19466               while (((MATRIX_ROW_CONTINUATION_LINE_P (row)
 19467                        || row->continued_p)
 19468                       && MATRIX_ROW_BOTTOM_Y (row) <= last_y)
 19469                      || (MATRIX_ROW_START_CHARPOS (row) == PT
 19470                          && MATRIX_ROW_BOTTOM_Y (row) < last_y));
 19471               /* If we didn't find any candidate rows, or exited the
 19472                  loop before all the candidates were examined, signal
 19473                  to the caller that this method failed.  */
 19474               if (rc != CURSOR_MOVEMENT_SUCCESS
 19475                   && !(rv
 19476                        && !MATRIX_ROW_CONTINUATION_LINE_P (row)
 19477                        && !row->continued_p))
 19478                 rc = CURSOR_MOVEMENT_MUST_SCROLL;
 19479               else if (rv)
 19480                 rc = CURSOR_MOVEMENT_SUCCESS;
 19481             }
 19482           else
 19483             {
 19484               do
 19485                 {
 19486                   if (set_cursor_from_row (w, row, w->current_matrix, 0, 0, 0, 0))
 19487                     {
 19488                       rc = CURSOR_MOVEMENT_SUCCESS;
 19489                       break;
 19490                     }
 19491                   ++row;
 19492                 }
 19493               while (MATRIX_ROW_BOTTOM_Y (row) < last_y
 19494                      && MATRIX_ROW_START_CHARPOS (row) == PT
 19495                      && cursor_row_p (row));
 19496             }
 19497         }
 19498     }
 19499 
 19500   return rc;
 19501 }
 19502 
 19503 
 19504 void
 19505 set_vertical_scroll_bar (struct window *w)
 19506 {
 19507   ptrdiff_t start, end, whole;
 19508 
 19509   /* Calculate the start and end positions for the current window.
 19510      At some point, it would be nice to choose between scrollbars
 19511      which reflect the whole buffer size, with special markers
 19512      indicating narrowing, and scrollbars which reflect only the
 19513      visible region.
 19514 
 19515      Note that mini-buffers sometimes aren't displaying any text.  */
 19516   if (!MINI_WINDOW_P (w)
 19517       || (w == XWINDOW (minibuf_window)
 19518           && NILP (echo_area_buffer[0])))
 19519     {
 19520       struct buffer *buf = XBUFFER (w->contents);
 19521 
 19522       whole = BUF_ZV (buf) - BUF_BEGV (buf);
 19523       start = marker_position (w->start) - BUF_BEGV (buf);
 19524       end = BUF_Z (buf) - w->window_end_pos - BUF_BEGV (buf);
 19525 
 19526       /* If w->window_end_pos cannot be trusted, recompute it "the
 19527          hard way".  But don't bother to be too accurate when
 19528          long-line shortcuts are in effect.  */
 19529       if (!w->window_end_valid && !buf->long_line_optimizations_p)
 19530         {
 19531           struct it it;
 19532           struct text_pos start_pos;
 19533           struct buffer *obuf = current_buffer;
 19534           /* When we display the scroll bar of a mini-window,
 19535              current_buffer is not guaranteed to be the mini-window's
 19536              buffer, see the beginning of redisplay_window.  */
 19537           set_buffer_internal_1 (XBUFFER (w->contents));
 19538           SET_TEXT_POS_FROM_MARKER (start_pos, w->start);
 19539           start_display (&it, w, start_pos);
 19540           move_it_to (&it, -1, it.last_visible_x, window_box_height (w), -1,
 19541                       MOVE_TO_X | MOVE_TO_Y);
 19542           end -= (BUF_Z (buf) - IT_CHARPOS (it)) - w->window_end_pos;
 19543           set_buffer_internal_1 (obuf);
 19544         }
 19545 
 19546       if (end < start)
 19547         end = start;
 19548       if (whole < (end - start))
 19549         whole = end - start;
 19550     }
 19551   else
 19552     start = end = whole = 0;
 19553 
 19554   /* Indicate what this scroll bar ought to be displaying now.  */
 19555   if (FRAME_TERMINAL (XFRAME (w->frame))->set_vertical_scroll_bar_hook)
 19556     (*FRAME_TERMINAL (XFRAME (w->frame))->set_vertical_scroll_bar_hook)
 19557       (w, end - start, whole, start);
 19558 }
 19559 
 19560 
 19561 void
 19562 set_horizontal_scroll_bar (struct window *w)
 19563 {
 19564   int start, end, whole, portion;
 19565 
 19566   if (!MINI_WINDOW_P (w) || EQ (w->horizontal_scroll_bar_type, Qbottom))
 19567     {
 19568       struct buffer *b = XBUFFER (w->contents);
 19569       struct buffer *old_buffer = NULL;
 19570       struct it it;
 19571       struct text_pos startp;
 19572 
 19573       if (b != current_buffer)
 19574         {
 19575           old_buffer = current_buffer;
 19576           set_buffer_internal (b);
 19577         }
 19578 
 19579       SET_TEXT_POS_FROM_MARKER (startp, w->start);
 19580       start_display (&it, w, startp);
 19581       it.last_visible_x = INT_MAX;
 19582       whole = move_it_to (&it, -1, INT_MAX, window_box_height (w), -1,
 19583                           MOVE_TO_X | MOVE_TO_Y);
 19584       /* whole = move_it_to (&it, w->window_end_pos, INT_MAX,
 19585                           window_box_height (w), -1,
 19586                           MOVE_TO_POS | MOVE_TO_X | MOVE_TO_Y); */
 19587 
 19588       start = w->hscroll * FRAME_COLUMN_WIDTH (WINDOW_XFRAME (w));
 19589       end = start + window_box_width (w, TEXT_AREA);
 19590       portion = end - start;
 19591       /* After enlarging a horizontally scrolled window such that it
 19592          gets at least as wide as the text it contains, make sure that
 19593          the thumb doesn't fill the entire scroll bar so we can still
 19594          drag it back to see the entire text.  */
 19595       whole = max (whole, end);
 19596 
 19597       if (it.bidi_p)
 19598         {
 19599           Lisp_Object pdir;
 19600 
 19601           pdir = Fcurrent_bidi_paragraph_direction (Qnil);
 19602           if (EQ (pdir, Qright_to_left))
 19603             {
 19604               start = whole - end;
 19605               end = start + portion;
 19606             }
 19607         }
 19608 
 19609       if (old_buffer)
 19610         set_buffer_internal (old_buffer);
 19611     }
 19612   else
 19613     start = end = whole = portion = 0;
 19614 
 19615   w->hscroll_whole = whole;
 19616 
 19617   /* Indicate what this scroll bar ought to be displaying now.  */
 19618   if (FRAME_TERMINAL (XFRAME (w->frame))->set_horizontal_scroll_bar_hook)
 19619     (*FRAME_TERMINAL (XFRAME (w->frame))->set_horizontal_scroll_bar_hook)
 19620       (w, portion, whole, start);
 19621 }
 19622 
 19623 /* Subroutine of redisplay_window, to determine whether a window-start
 19624    point STARTP of WINDOW should be rejected.  */
 19625 static bool
 19626 window_start_acceptable_p (Lisp_Object window, ptrdiff_t startp)
 19627 {
 19628   if (!make_window_start_visible)
 19629     return true;
 19630 
 19631   struct window *w = XWINDOW (window);
 19632   struct frame *f = XFRAME (w->frame);
 19633   Lisp_Object startpos = make_fixnum (startp);
 19634   Lisp_Object invprop, disp_spec;
 19635   struct text_pos ignored;
 19636 
 19637   /* Is STARTP in invisible text?  */
 19638   if ((invprop = Fget_char_property (startpos, Qinvisible, window)),
 19639       TEXT_PROP_MEANS_INVISIBLE (invprop) != 0)
 19640     return false;
 19641 
 19642   /* Is STARTP covered by a replacing 'display' property?  */
 19643   if (!NILP (disp_spec = Fget_char_property (startpos, Qdisplay, window))
 19644       && handle_display_spec (NULL, disp_spec, Qnil, Qnil, &ignored, startp,
 19645                               FRAME_WINDOW_P (f)) > 0)
 19646     return false;
 19647 
 19648   return true;
 19649 }
 19650 
 19651 DEFUN ("long-line-optimizations-p", Flong_line_optimizations_p, Slong_line_optimizations_p,
 19652        0, 0, 0,
 19653        doc: /* Return non-nil if long-line optimizations are in effect in current buffer.
 19654 See `long-line-threshold' and `large-hscroll-threshold' for what these
 19655 optimizations mean and when they are in effect.  */)
 19656   (void)
 19657 {
 19658   return current_buffer->long_line_optimizations_p ? Qt : Qnil;
 19659 }
 19660 
 19661 /* Redisplay leaf window WINDOW.  JUST_THIS_ONE_P means only
 19662    selected_window is redisplayed.
 19663 
 19664    We can return without actually redisplaying the window if fonts has been
 19665    changed on window's frame.  In that case, redisplay_internal will retry.
 19666 
 19667    As one of the important parts of redisplaying a window, we need to
 19668    decide whether the previous window-start position (stored in the
 19669    window's w->start marker position) is still valid, and if it isn't,
 19670    recompute it.  Some details about that:
 19671 
 19672     . The previous window-start could be in a continuation line, in
 19673       which case we need to recompute it when the window width
 19674       changes.  See compute_window_start_on_continuation_line and its
 19675       call below.
 19676 
 19677     . The text that changed since last redisplay could include the
 19678       previous window-start position.  In that case, we try to salvage
 19679       what we can from the current glyph matrix by calling
 19680       try_scrolling, which see.
 19681 
 19682     . Some Emacs command could force us to use a specific window-start
 19683       position by setting the window's force_start flag, or gently
 19684       propose doing that by setting the window's optional_new_start
 19685       flag.  In these cases, we try using the specified start point if
 19686       that succeeds (i.e. the window desired matrix is successfully
 19687       recomputed, and point location is within the window).  In case
 19688       of optional_new_start, we first check if the specified start
 19689       position is feasible, i.e. if it will allow point to be
 19690       displayed in the window.  If using the specified start point
 19691       fails, e.g., if new fonts are needed to be loaded, we abort the
 19692       redisplay cycle and leave it up to the next cycle to figure out
 19693       things.
 19694 
 19695     . Note that the window's force_start flag is sometimes set by
 19696       redisplay itself, when it decides that the previous window start
 19697       point is fine and should be kept.  Search for "goto force_start"
 19698       below to see the details.  Like the values of window-start
 19699       specified outside of redisplay, these internally-deduced values
 19700       are tested for feasibility, and ignored if found to be
 19701       unfeasible.
 19702 
 19703     . Note that the function try_window, used to completely redisplay
 19704       a window, accepts the window's start point as its argument.
 19705       This is used several times in the redisplay code to control
 19706       where the window start will be, according to user options such
 19707       as scroll-conservatively, and also to ensure the screen line
 19708       showing point will be fully (as opposed to partially) visible on
 19709       display.  */
 19710 
 19711 static void
 19712 redisplay_window (Lisp_Object window, bool just_this_one_p)
 19713 {
 19714   struct window *w = XWINDOW (window);
 19715   struct frame *f = XFRAME (w->frame);
 19716   struct buffer *buffer = XBUFFER (w->contents);
 19717   struct buffer *old = current_buffer;
 19718   struct text_pos lpoint, opoint, startp;
 19719   bool update_mode_line;
 19720   int tem;
 19721   struct it it;
 19722   /* Record it now because it's overwritten.  */
 19723   bool current_matrix_up_to_date_p = false;
 19724   bool used_current_matrix_p = false;
 19725   /* This is less strict than current_matrix_up_to_date_p.
 19726      It indicates that the buffer contents and narrowing are unchanged.  */
 19727   bool buffer_unchanged_p = false;
 19728   bool temp_scroll_step = false;
 19729   specpdl_ref count = SPECPDL_INDEX ();
 19730   int rc;
 19731   int centering_position = -1;
 19732   bool last_line_misfit = false;
 19733   ptrdiff_t beg_unchanged, end_unchanged;
 19734   int frame_line_height, margin;
 19735   bool use_desired_matrix;
 19736   void *itdata = NULL;
 19737 
 19738   SET_TEXT_POS (lpoint, PT, PT_BYTE);
 19739   opoint = lpoint;
 19740 
 19741 #ifdef GLYPH_DEBUG
 19742   *w->desired_matrix->method = 0;
 19743 #endif
 19744 
 19745   if (!just_this_one_p && needs_no_redisplay (w))
 19746     return;
 19747 
 19748   /* Make sure that both W's markers are valid.  */
 19749   eassert (XMARKER (w->start)->buffer == buffer);
 19750   eassert (XMARKER (w->pointm)->buffer == buffer);
 19751 
 19752   reconsider_clip_changes (w);
 19753   frame_line_height = default_line_pixel_height (w);
 19754   margin = window_scroll_margin (w, MARGIN_IN_LINES);
 19755 
 19756 
 19757   /* Has the mode line to be updated?  */
 19758   update_mode_line = (w->update_mode_line
 19759                       || update_mode_lines
 19760                       || buffer->clip_changed
 19761                       || buffer->prevent_redisplay_optimizations_p);
 19762 
 19763   if (!just_this_one_p)
 19764     /* If `just_this_one_p' is set, we apparently set must_be_updated_p more
 19765        cleverly elsewhere.  */
 19766     w->must_be_updated_p = true;
 19767 
 19768   if (MINI_WINDOW_P (w))
 19769     {
 19770       if (w == XWINDOW (echo_area_window)
 19771           && !NILP (echo_area_buffer[0]))
 19772         {
 19773           if (update_mode_line)
 19774             /* We may have to update a tty frame's menu bar or a
 19775                tool-bar.  Example `M-x C-h C-h C-g'.  */
 19776             goto finish_menu_bars;
 19777           else
 19778             /* We've already displayed the echo area glyphs in this window.  */
 19779             goto finish_scroll_bars;
 19780         }
 19781       else if ((w != XWINDOW (minibuf_window)
 19782                 || minibuf_level == 0)
 19783                /* When buffer is nonempty, redisplay window normally.  */
 19784                && BUF_Z (XBUFFER (w->contents)) == BUF_BEG (XBUFFER (w->contents))
 19785                /* Quail displays non-mini buffers in minibuffer window.
 19786                   In that case, redisplay the window normally.  */
 19787                && !NILP (Fmemq (w->contents, Vminibuffer_list)))
 19788         {
 19789           /* W is a mini-buffer window, but it's not active, so clear
 19790              it.  */
 19791           int yb = window_text_bottom_y (w);
 19792           struct glyph_row *row;
 19793           int y;
 19794 
 19795           for (y = 0, row = w->desired_matrix->rows;
 19796                y < yb;
 19797                y += row->height, ++row)
 19798             blank_row (w, row, y);
 19799           goto finish_scroll_bars;
 19800         }
 19801       else if (minibuf_level >= 1)
 19802         {
 19803           /* We could have a message produced by set-minibuffer-message
 19804              displayed in the mini-window as an overlay, so resize the
 19805              mini-window if needed.  */
 19806           resize_mini_window (w, false);
 19807         }
 19808 
 19809       clear_glyph_matrix (w->desired_matrix);
 19810     }
 19811 
 19812   /* Otherwise set up data on this window; select its buffer and point
 19813      value.  */
 19814   /* Really select the buffer, for the sake of buffer-local
 19815      variables.  */
 19816   set_buffer_internal_1 (XBUFFER (w->contents));
 19817 
 19818   current_matrix_up_to_date_p
 19819     = (w->window_end_valid
 19820        && !current_buffer->clip_changed
 19821        && !current_buffer->prevent_redisplay_optimizations_p
 19822        && !window_outdated (w)
 19823        && !composition_break_at_point
 19824        && !hscrolling_current_line_p (w));
 19825 
 19826   beg_unchanged = BEG_UNCHANGED;
 19827   end_unchanged = END_UNCHANGED;
 19828 
 19829   SET_TEXT_POS (opoint, PT, PT_BYTE);
 19830 
 19831   specbind (Qinhibit_point_motion_hooks, Qt);
 19832 
 19833   buffer_unchanged_p
 19834     = (w->window_end_valid
 19835        && !current_buffer->clip_changed
 19836        && !window_outdated (w));
 19837 
 19838   /* When windows_or_buffers_changed is non-zero, we can't rely
 19839      on the window end being valid, so set it to zero there.  */
 19840   if (windows_or_buffers_changed)
 19841     {
 19842       /* If window starts on a continuation line, maybe adjust the
 19843          window start in case the window's width changed.  */
 19844       if (XMARKER (w->start)->buffer == current_buffer)
 19845         compute_window_start_on_continuation_line (w);
 19846 
 19847       w->window_end_valid = false;
 19848       /* If so, we also can't rely on current matrix
 19849          and should not fool try_cursor_movement below.  */
 19850       current_matrix_up_to_date_p = false;
 19851     }
 19852 
 19853   /* Some sanity checks.  */
 19854   CHECK_WINDOW_END (w);
 19855   if (Z == Z_BYTE && CHARPOS (opoint) != BYTEPOS (opoint))
 19856     emacs_abort ();
 19857   if (BYTEPOS (opoint) < CHARPOS (opoint))
 19858     emacs_abort ();
 19859 
 19860   if (mode_line_update_needed (w))
 19861     update_mode_line = true;
 19862 
 19863   /* Point refers normally to the selected window.  For any other
 19864      window, set up appropriate value.  */
 19865   if (!EQ (window, selected_window))
 19866     {
 19867       ptrdiff_t new_pt = marker_position (w->pointm);
 19868       ptrdiff_t new_pt_byte = marker_byte_position (w->pointm);
 19869 
 19870       if (new_pt < BEGV)
 19871         {
 19872           new_pt = BEGV;
 19873           new_pt_byte = BEGV_BYTE;
 19874           set_marker_both (w->pointm, Qnil, BEGV, BEGV_BYTE);
 19875         }
 19876       else if (new_pt > (ZV - 1))
 19877         {
 19878           new_pt = ZV;
 19879           new_pt_byte = ZV_BYTE;
 19880           set_marker_both (w->pointm, Qnil, ZV, ZV_BYTE);
 19881         }
 19882 
 19883       /* We don't use SET_PT so that the point-motion hooks don't run.  */
 19884       TEMP_SET_PT_BOTH (new_pt, new_pt_byte);
 19885     }
 19886 
 19887   /* If any of the character widths specified in the display table
 19888      have changed, invalidate the width run cache.  It's true that
 19889      this may be a bit late to catch such changes, but the rest of
 19890      redisplay goes (non-fatally) haywire when the display table is
 19891      changed, so why should we worry about doing any better?  */
 19892   if (current_buffer->width_run_cache
 19893       || (current_buffer->base_buffer
 19894           && current_buffer->base_buffer->width_run_cache))
 19895     {
 19896       struct Lisp_Char_Table *disptab = buffer_display_table ();
 19897 
 19898       if (! disptab_matches_widthtab
 19899           (disptab, XVECTOR (BVAR (current_buffer, width_table))))
 19900         {
 19901           struct buffer *buf = current_buffer;
 19902 
 19903           if (buf->base_buffer)
 19904             buf = buf->base_buffer;
 19905           invalidate_region_cache (buf, buf->width_run_cache, BEG, Z);
 19906           recompute_width_table (current_buffer, disptab);
 19907         }
 19908     }
 19909 
 19910   /* Check whether the buffer to be displayed contains long lines.  */
 19911   if (!NILP (Vlong_line_threshold)
 19912       && !current_buffer->long_line_optimizations_p
 19913       && (CHARS_MODIFF - UNCHANGED_MODIFIED > 8
 19914           || current_buffer->clip_changed))
 19915     {
 19916       ptrdiff_t cur, next, found, max = 0, threshold;
 19917       threshold = XFIXNUM (Vlong_line_threshold);
 19918       for (cur = BEGV; cur < ZV; cur = next)
 19919         {
 19920           next = find_newline1 (cur, CHAR_TO_BYTE (cur), 0, -1, 1,
 19921                                 &found, NULL, true);
 19922           if (next - cur > max) max = next - cur;
 19923           if (!found || max > threshold) break;
 19924         }
 19925       if (max > threshold)
 19926         current_buffer->long_line_optimizations_p = true;
 19927     }
 19928 
 19929   /* If window-start is screwed up, choose a new one.  */
 19930   if (XMARKER (w->start)->buffer != current_buffer)
 19931     goto recenter;
 19932 
 19933   SET_TEXT_POS_FROM_MARKER (startp, w->start);
 19934 
 19935   /* If someone specified a new starting point but did not insist,
 19936      check whether it can be used.  */
 19937   if ((w->optional_new_start || window_frozen_p (w))
 19938       && CHARPOS (startp) >= BEGV
 19939       && CHARPOS (startp) <= ZV)
 19940     {
 19941       ptrdiff_t it_charpos;
 19942 
 19943       w->optional_new_start = false;
 19944       if (!w->force_start)
 19945         {
 19946           start_display (&it, w, startp);
 19947           move_it_to (&it, PT, 0, it.last_visible_y, -1,
 19948                       MOVE_TO_POS | MOVE_TO_X | MOVE_TO_Y);
 19949           /* Record IT's position now, since line_bottom_y might
 19950              change that.  */
 19951           it_charpos = IT_CHARPOS (it);
 19952           /* Make sure we set the force_start flag only if the cursor
 19953              row will be fully visible.  Otherwise, the code under
 19954              force_start label below will try to move point back into
 19955              view, which is not what the code which sets
 19956              optional_new_start wants.  */
 19957           if (it.current_y == 0 || line_bottom_y (&it) < it.last_visible_y)
 19958             {
 19959               if (it_charpos == PT)
 19960                 w->force_start = true;
 19961               /* IT may overshoot PT if text at PT is invisible.  */
 19962               else if (it_charpos > PT && CHARPOS (startp) <= PT)
 19963                 w->force_start = true;
 19964 #ifdef GLYPH_DEBUG
 19965               if (w->force_start)
 19966                 {
 19967                   if (window_frozen_p (w))
 19968                     debug_method_add (w, "set force_start from frozen window start");
 19969                   else
 19970                     debug_method_add (w, "set force_start from optional_new_start");
 19971                 }
 19972 #endif
 19973             }
 19974         }
 19975     }
 19976 
 19977  force_start:
 19978 
 19979   /* Handle case where place to start displaying has been specified,
 19980      unless the specified location is outside the accessible range.  */
 19981   if (w->force_start)
 19982     {
 19983       /* We set this later on if we have to adjust point.  */
 19984       int new_vpos = -1;
 19985 
 19986       w->force_start = false;
 19987 
 19988       /* The vscroll should be preserved in this case, since
 19989          `pixel-scroll-precision-mode' must continue working normally
 19990          when a mini-window is resized.  (bug#55312) */
 19991       if (!w->preserve_vscroll_p || !window_frozen_p (w))
 19992         w->vscroll = 0;
 19993 
 19994       w->preserve_vscroll_p = false;
 19995       w->window_end_valid = false;
 19996 
 19997       /* Forget any recorded base line for line number display.  */
 19998       if (!buffer_unchanged_p)
 19999         w->base_line_number = 0;
 20000 
 20001       /* Redisplay the mode line.  Select the buffer properly for that.
 20002          Also, run the hook window-scroll-functions
 20003          because we have scrolled.  */
 20004       /* Note, we do this after clearing force_start because
 20005          if there's an error, it is better to forget about force_start
 20006          than to get into an infinite loop calling the hook functions
 20007          and having them get more errors.  */
 20008       if (!update_mode_line
 20009           || ! NILP (Vwindow_scroll_functions))
 20010         {
 20011           update_mode_line = true;
 20012           w->update_mode_line = true;
 20013           startp = run_window_scroll_functions (window, startp);
 20014         }
 20015 
 20016       if (CHARPOS (startp) < BEGV)
 20017         SET_TEXT_POS (startp, BEGV, BEGV_BYTE);
 20018       else if (CHARPOS (startp) > ZV)
 20019         SET_TEXT_POS (startp, ZV, ZV_BYTE);
 20020 
 20021       /* Reject the specified start location if it is invisible, and
 20022          the buffer wants it always visible.  */
 20023       if (!window_start_acceptable_p (window, CHARPOS (startp)))
 20024         goto ignore_start;
 20025 
 20026       /* Redisplay, then check if cursor has been set during the
 20027          redisplay.  Give up if new fonts were loaded.  */
 20028       /* We used to issue a CHECK_MARGINS argument to try_window here,
 20029          but this causes scrolling to fail when point begins inside
 20030          the scroll margin (bug#148) -- cyd  */
 20031       clear_glyph_matrix (w->desired_matrix);
 20032       if (!try_window (window, startp, 0))
 20033         {
 20034           w->force_start = true;
 20035           clear_glyph_matrix (w->desired_matrix);
 20036           goto need_larger_matrices;
 20037         }
 20038 
 20039       if (w->cursor.vpos < 0)
 20040         {
 20041           /* If point does not appear, try to move point so it does
 20042              appear.  The desired matrix has been built above, so we
 20043              can use it here.  First see if point is in invisible
 20044              text, and if so, move it to the first visible buffer
 20045              position past that.  */
 20046           struct glyph_row *r = NULL;
 20047           Lisp_Object invprop =
 20048             get_char_property_and_overlay (make_fixnum (PT), Qinvisible,
 20049                                            Qnil, NULL);
 20050 
 20051           if (TEXT_PROP_MEANS_INVISIBLE (invprop) != 0)
 20052             {
 20053               ptrdiff_t alt_pt;
 20054               Lisp_Object invprop_end =
 20055                 Fnext_single_char_property_change (make_fixnum (PT), Qinvisible,
 20056                                                    Qnil, Qnil);
 20057 
 20058               if (FIXNATP (invprop_end))
 20059                 alt_pt = XFIXNAT (invprop_end);
 20060               else
 20061                 alt_pt = ZV;
 20062               r = row_containing_pos (w, alt_pt, w->desired_matrix->rows,
 20063                                       NULL, 0);
 20064             }
 20065           if (r)
 20066             new_vpos = MATRIX_ROW_BOTTOM_Y (r);
 20067           else  /* Give up and just move to the middle of the window.  */
 20068             new_vpos = window_box_height (w) / 2;
 20069         }
 20070 
 20071       if (!cursor_row_fully_visible_p (w, false, false, false))
 20072         {
 20073           /* Point does appear, but on a line partly visible at end of window.
 20074              Move it back to a fully-visible line.  */
 20075           new_vpos = window_box_height (w);
 20076           /* But if window_box_height suggests a Y coordinate that is
 20077              not less than we already have, that line will clearly not
 20078              be fully visible, so give up and scroll the display.
 20079              This can happen when the default face uses a font whose
 20080              dimensions are different from the frame's default
 20081              font.  */
 20082           if (new_vpos >= w->cursor.y)
 20083             {
 20084               w->cursor.vpos = -1;
 20085               clear_glyph_matrix (w->desired_matrix);
 20086               goto try_to_scroll;
 20087             }
 20088         }
 20089       else if (w->cursor.vpos >= 0)
 20090         {
 20091           /* Some people insist on not letting point enter the scroll
 20092              margin, even though this part handles windows that didn't
 20093              scroll at all.  */
 20094           int pixel_margin = margin * frame_line_height;
 20095           bool tab_line = window_wants_tab_line (w);
 20096           bool header_line = window_wants_header_line (w);
 20097 
 20098           /* Note: We add an extra FRAME_LINE_HEIGHT, because the loop
 20099              below, which finds the row to move point to, advances by
 20100              the Y coordinate of the _next_ row, see the definition of
 20101              MATRIX_ROW_BOTTOM_Y.  */
 20102           if (w->cursor.vpos < margin + tab_line + header_line)
 20103             {
 20104               w->cursor.vpos = -1;
 20105               clear_glyph_matrix (w->desired_matrix);
 20106               goto try_to_scroll;
 20107             }
 20108           else
 20109             {
 20110               int window_height = window_box_height (w);
 20111 
 20112               if (tab_line)
 20113                 window_height += CURRENT_TAB_LINE_HEIGHT (w);
 20114               if (header_line)
 20115                 window_height += CURRENT_HEADER_LINE_HEIGHT (w);
 20116               if (w->cursor.y >= window_height - pixel_margin)
 20117                 {
 20118                   w->cursor.vpos = -1;
 20119                   clear_glyph_matrix (w->desired_matrix);
 20120                   goto try_to_scroll;
 20121                 }
 20122             }
 20123         }
 20124 
 20125       /* If we need to move point for either of the above reasons,
 20126          now actually do it.  */
 20127       if (new_vpos >= 0)
 20128         {
 20129           struct glyph_row *row;
 20130 
 20131           row = MATRIX_FIRST_TEXT_ROW (w->desired_matrix);
 20132           while (MATRIX_ROW_BOTTOM_Y (row) < new_vpos
 20133                  && !row->ends_at_zv_p)
 20134             ++row;
 20135 
 20136           TEMP_SET_PT_BOTH (MATRIX_ROW_START_CHARPOS (row),
 20137                             MATRIX_ROW_START_BYTEPOS (row));
 20138 
 20139           if (w != XWINDOW (selected_window))
 20140             set_marker_both (w->pointm, Qnil, PT, PT_BYTE);
 20141           else if (current_buffer == old)
 20142             SET_TEXT_POS (lpoint, PT, PT_BYTE);
 20143 
 20144           set_cursor_from_row (w, row, w->desired_matrix, 0, 0, 0, 0);
 20145 
 20146           /* Re-run pre-redisplay-function so it can update the region
 20147              according to the new position of point.  */
 20148           /* Other than the cursor, w's redisplay is done so we can set its
 20149              redisplay to false.  Also the buffer's redisplay can be set to
 20150              false, since propagate_buffer_redisplay should have already
 20151              propagated its info to `w' anyway.  */
 20152           w->redisplay = false;
 20153           XBUFFER (w->contents)->text->redisplay = false;
 20154           safe__call1 (true, Vpre_redisplay_function, Fcons (window, Qnil));
 20155 
 20156           if (w->redisplay || XBUFFER (w->contents)->text->redisplay
 20157               || ((EQ (Vdisplay_line_numbers, Qrelative)
 20158                    || EQ (Vdisplay_line_numbers, Qvisual))
 20159                   && row != MATRIX_FIRST_TEXT_ROW (w->desired_matrix)))
 20160             {
 20161               /* Either pre-redisplay-function made changes (e.g. move
 20162                  the region), or we moved point in a window that is
 20163                  under display-line-numbers = relative mode.  We need
 20164                  another round of redisplay.  */
 20165               clear_glyph_matrix (w->desired_matrix);
 20166               if (!try_window (window, startp, 0))
 20167                 goto need_larger_matrices;
 20168             }
 20169         }
 20170       if (w->cursor.vpos < 0
 20171           || !cursor_row_fully_visible_p (w, false, false, false))
 20172         {
 20173           clear_glyph_matrix (w->desired_matrix);
 20174           goto try_to_scroll;
 20175         }
 20176 
 20177 #ifdef GLYPH_DEBUG
 20178       debug_method_add (w, "forced window start");
 20179 #endif
 20180       goto done;
 20181     }
 20182 
 20183  ignore_start:
 20184 
 20185   /* Handle case where text has not changed, only point, and it has
 20186      not moved off the frame, and we are not retrying after hscroll.
 20187      (current_matrix_up_to_date_p is true when retrying.)  */
 20188   if (current_matrix_up_to_date_p
 20189       && (rc = try_cursor_movement (window, startp, &temp_scroll_step),
 20190           rc != CURSOR_MOVEMENT_CANNOT_BE_USED))
 20191     {
 20192       switch (rc)
 20193         {
 20194         case CURSOR_MOVEMENT_SUCCESS:
 20195           used_current_matrix_p = true;
 20196           goto done;
 20197 
 20198         case CURSOR_MOVEMENT_MUST_SCROLL:
 20199           goto try_to_scroll;
 20200 
 20201         default:
 20202           emacs_abort ();
 20203         }
 20204     }
 20205   /* If current starting point was originally the beginning of a line
 20206      but no longer is, or if the starting point is invisible but the
 20207      buffer wants it always visible, find a new starting point.  */
 20208   else if (w->start_at_line_beg
 20209            && ((CHARPOS (startp) > BEGV
 20210                 && FETCH_BYTE (BYTEPOS (startp) - 1) != '\n')
 20211                || (CHARPOS (startp) >= BEGV
 20212                    && CHARPOS (startp) <= ZV
 20213                    && !window_start_acceptable_p (window, CHARPOS (startp)))))
 20214     {
 20215 #ifdef GLYPH_DEBUG
 20216       debug_method_add (w, "recenter 1");
 20217 #endif
 20218       goto recenter;
 20219     }
 20220 
 20221   /* Try scrolling with try_window_id.  Value is > 0 if update has
 20222      been done, it is -1 if we know that the same window start will
 20223      not work.  It is 0 if unsuccessful for some other reason.  */
 20224   else if ((tem = try_window_id (w)) != 0)
 20225     {
 20226 #ifdef GLYPH_DEBUG
 20227       debug_method_add (w, "try_window_id %d", tem);
 20228 #endif
 20229 
 20230       if (f->fonts_changed)
 20231         goto need_larger_matrices;
 20232       if (tem > 0)
 20233         goto done;
 20234 
 20235       /* Otherwise try_window_id has returned -1 which means that we
 20236          don't want the alternative below this comment to execute.  */
 20237     }
 20238   else if (CHARPOS (startp) >= BEGV
 20239            && CHARPOS (startp) <= ZV
 20240            && PT >= CHARPOS (startp)
 20241            && (CHARPOS (startp) < ZV
 20242                /* Avoid starting at end of buffer.  */
 20243                || CHARPOS (startp) == BEGV
 20244                || !window_outdated (w)))
 20245     {
 20246       int d1, d2, d5, d6;
 20247       int rtop, rbot;
 20248 
 20249       /* If first window line is a continuation line, and window start
 20250          is inside the modified region, but the first change is before
 20251          current window start, we must select a new window start.
 20252 
 20253          However, if this is the result of a down-mouse event (e.g. by
 20254          extending the mouse-drag-overlay), we don't want to select a
 20255          new window start, since that would change the position under
 20256          the mouse, resulting in an unwanted mouse-movement rather
 20257          than a simple mouse-click.  */
 20258       if (!w->start_at_line_beg
 20259           && NILP (track_mouse)
 20260           && CHARPOS (startp) > BEGV
 20261           && CHARPOS (startp) > BEG + beg_unchanged
 20262           && CHARPOS (startp) <= Z - end_unchanged
 20263           /* Even if w->start_at_line_beg is nil, a new window may
 20264              start at a line_beg, since that's how set_buffer_window
 20265              sets it.  So, we need to check the return value of
 20266              compute_window_start_on_continuation_line.  (See also
 20267              bug#197).  */
 20268           && XMARKER (w->start)->buffer == current_buffer
 20269           && compute_window_start_on_continuation_line (w)
 20270           /* It doesn't make sense to force the window start like we
 20271              do at label force_start if it is already known that point
 20272              will not be fully visible in the resulting window, because
 20273              doing so will move point from its correct position
 20274              instead of scrolling the window to bring point into view.
 20275              See bug#9324.  */
 20276           && pos_visible_p (w, PT, &d1, &d2, &rtop, &rbot, &d5, &d6)
 20277           /* A very tall row could need more than the window height,
 20278              in which case we accept that it is partially visible.  */
 20279           && (rtop != 0) == (rbot != 0))
 20280         {
 20281           w->force_start = true;
 20282           SET_TEXT_POS_FROM_MARKER (startp, w->start);
 20283 #ifdef GLYPH_DEBUG
 20284           debug_method_add (w, "recomputed window start in continuation line");
 20285 #endif
 20286           goto force_start;
 20287         }
 20288 
 20289       /* Don't use the same window-start if it is invisible or covered
 20290          by a replacing 'display' property and the buffer requested
 20291          the window-start to be always visible.  */
 20292       if (!window_start_acceptable_p (window, CHARPOS (startp)))
 20293         {
 20294 #ifdef GLYPH_DEBUG
 20295           debug_method_add (w, "recenter 2");
 20296 #endif
 20297           goto recenter;
 20298         }
 20299 
 20300 #ifdef GLYPH_DEBUG
 20301       debug_method_add (w, "same window start");
 20302 #endif
 20303 
 20304       /* Try to redisplay starting at same place as before.
 20305          If point has not moved off frame, accept the results.  */
 20306       if (!current_matrix_up_to_date_p
 20307           /* Don't use try_window_reusing_current_matrix in this case
 20308              because a window scroll function can have changed the
 20309              buffer.  */
 20310           || !NILP (Vwindow_scroll_functions)
 20311           || MINI_WINDOW_P (w)
 20312           || !(used_current_matrix_p
 20313                = try_window_reusing_current_matrix (w)))
 20314         {
 20315           IF_DEBUG (debug_method_add (w, "1"));
 20316           clear_glyph_matrix (w->desired_matrix);
 20317           if (try_window (window, startp, TRY_WINDOW_CHECK_MARGINS) < 0)
 20318             /* -1 means we need to scroll.
 20319                0 means we need new matrices, but fonts_changed
 20320                is set in that case, so we will detect it below.  */
 20321             goto try_to_scroll;
 20322         }
 20323 
 20324       if (f->fonts_changed)
 20325         goto need_larger_matrices;
 20326 
 20327       if (w->cursor.vpos >= 0)
 20328         {
 20329           if (!just_this_one_p
 20330               || current_buffer->clip_changed
 20331               || BEG_UNCHANGED < CHARPOS (startp))
 20332             /* Forget any recorded base line for line number display.  */
 20333             w->base_line_number = 0;
 20334 
 20335           if (!cursor_row_fully_visible_p (w, true, false, false))
 20336             {
 20337               clear_glyph_matrix (w->desired_matrix);
 20338               last_line_misfit = true;
 20339             }
 20340             /* Drop through and scroll.  */
 20341           else
 20342             goto done;
 20343         }
 20344       else
 20345         clear_glyph_matrix (w->desired_matrix);
 20346     }
 20347 
 20348  try_to_scroll:
 20349 
 20350   /* Redisplay the mode line.  Select the buffer properly for that.  */
 20351   if (!update_mode_line)
 20352     {
 20353       update_mode_line = true;
 20354       w->update_mode_line = true;
 20355     }
 20356 
 20357   /* Try to scroll by specified few lines.  */
 20358   if ((0 < scroll_conservatively
 20359        /* FIXME: the option is supposed to affect minibuffers, but we
 20360           test MINI_WINDOW_P, which can also catch uses of
 20361           mini-windows for displaying the echo area.  Do we need to
 20362           distinguish these two use cases?  */
 20363        || (scroll_minibuffer_conservatively && MINI_WINDOW_P (w))
 20364        || 0 < emacs_scroll_step
 20365        || temp_scroll_step
 20366        || NUMBERP (BVAR (current_buffer, scroll_up_aggressively))
 20367        || NUMBERP (BVAR (current_buffer, scroll_down_aggressively)))
 20368       && CHARPOS (startp) >= BEGV
 20369       && CHARPOS (startp) <= ZV)
 20370     {
 20371       /* The function returns -1 if new fonts were loaded, 1 if
 20372          successful, 0 if not successful.  */
 20373       int ss = try_scrolling (window, just_this_one_p,
 20374                               ((scroll_minibuffer_conservatively
 20375                                 && MINI_WINDOW_P (w))
 20376                                ? SCROLL_LIMIT + 1
 20377                                : scroll_conservatively),
 20378                               emacs_scroll_step,
 20379                               temp_scroll_step, last_line_misfit);
 20380       switch (ss)
 20381         {
 20382         case SCROLLING_SUCCESS:
 20383           goto done;
 20384 
 20385         case SCROLLING_NEED_LARGER_MATRICES:
 20386           goto need_larger_matrices;
 20387 
 20388         case SCROLLING_FAILED:
 20389           break;
 20390 
 20391         default:
 20392           emacs_abort ();
 20393         }
 20394     }
 20395 
 20396   /* Finally, just choose a place to start which positions point
 20397      according to user preferences.  */
 20398 
 20399  recenter:
 20400 
 20401 #ifdef GLYPH_DEBUG
 20402   debug_method_add (w, "recenter");
 20403 #endif
 20404 
 20405   /* Forget any previously recorded base line for line number display.  */
 20406   if (!buffer_unchanged_p)
 20407     w->base_line_number = 0;
 20408 
 20409   /* Determine the window start relative to point.  */
 20410   init_iterator (&it, w, PT, PT_BYTE, NULL, DEFAULT_FACE_ID);
 20411   it.current_y = it.last_visible_y;
 20412   if (centering_position < 0)
 20413     {
 20414       ptrdiff_t margin_pos = CHARPOS (startp);
 20415       Lisp_Object aggressive;
 20416       bool scrolling_up;
 20417 
 20418       /* If there is a scroll margin at the top of the window, find
 20419          its character position.  */
 20420       if (margin
 20421           /* Cannot call start_display if startp is not in the
 20422              accessible region of the buffer.  This can happen when we
 20423              have just switched to a different buffer and/or changed
 20424              its restriction.  In that case, startp is initialized to
 20425              the character position 1 (BEGV) because we did not yet
 20426              have chance to display the buffer even once.  */
 20427           && BEGV <= CHARPOS (startp) && CHARPOS (startp) <= ZV)
 20428         {
 20429           struct it it1;
 20430           void *it1data = NULL;
 20431 
 20432           SAVE_IT (it1, it, it1data);
 20433           start_display (&it1, w, startp);
 20434           move_it_vertically (&it1, margin * frame_line_height);
 20435           margin_pos = IT_CHARPOS (it1);
 20436           RESTORE_IT (&it, &it, it1data);
 20437         }
 20438       scrolling_up = PT > margin_pos;
 20439       aggressive =
 20440         scrolling_up
 20441         ? BVAR (current_buffer, scroll_up_aggressively)
 20442         : BVAR (current_buffer, scroll_down_aggressively);
 20443 
 20444       if (!MINI_WINDOW_P (w)
 20445           && (scroll_conservatively > SCROLL_LIMIT || NUMBERP (aggressive)))
 20446         {
 20447           int pt_offset = 0;
 20448 
 20449           /* Setting scroll-conservatively overrides
 20450              scroll-*-aggressively.  */
 20451           if (!scroll_conservatively && NUMBERP (aggressive))
 20452             {
 20453               double float_amount = XFLOATINT (aggressive);
 20454 
 20455               pt_offset = float_amount * WINDOW_BOX_TEXT_HEIGHT (w);
 20456               if (pt_offset == 0 && float_amount > 0)
 20457                 pt_offset = 1;
 20458               if (pt_offset && margin > 0)
 20459                 margin -= 1;
 20460             }
 20461           /* Compute how much to move the window start backward from
 20462              point so that point will be displayed where the user
 20463              wants it.  */
 20464           if (scrolling_up)
 20465             {
 20466               centering_position = it.last_visible_y;
 20467               if (pt_offset)
 20468                 centering_position -= pt_offset;
 20469               centering_position -=
 20470                 (frame_line_height * (1 + margin + last_line_misfit)
 20471                  + WINDOW_TAB_LINE_HEIGHT (w) + WINDOW_HEADER_LINE_HEIGHT (w));
 20472               /* Don't let point enter the scroll margin near top of
 20473                  the window.  */
 20474               if (centering_position < margin * frame_line_height)
 20475                 centering_position = margin * frame_line_height;
 20476             }
 20477           else
 20478             centering_position = margin * frame_line_height + pt_offset;
 20479         }
 20480       else
 20481         /* Set the window start half the height of the window backward
 20482            from point.  */
 20483         centering_position = window_box_height (w) / 2;
 20484     }
 20485   if (current_buffer->long_line_optimizations_p
 20486       && it.line_wrap == TRUNCATE)
 20487     {
 20488       /* For very long and truncated lines, go back using a simplified
 20489          method, which ignored any inaccuracies due to line-height
 20490          differences, display properties/overlays, etc.  */
 20491       int nlines = centering_position / frame_line_height;
 20492 
 20493       while (nlines-- && IT_CHARPOS (it) > BEGV)
 20494         back_to_previous_visible_line_start (&it);
 20495       reseat_1 (&it, it.current.pos, true);
 20496     }
 20497   else
 20498     move_it_vertically_backward (&it, centering_position);
 20499 
 20500   eassert (IT_CHARPOS (it) >= BEGV);
 20501 
 20502   /* The function move_it_vertically_backward may move over more
 20503      than the specified y-distance.  If it->w is small, e.g. a
 20504      mini-buffer window, we may end up in front of the window's
 20505      display area.  Start displaying at the start of the line
 20506      containing PT in this case.  */
 20507   if (it.current_y <= 0)
 20508     {
 20509       init_iterator (&it, w, PT, PT_BYTE, NULL, DEFAULT_FACE_ID);
 20510       move_it_vertically_backward (&it, 0);
 20511       it.current_y = 0;
 20512     }
 20513 
 20514   it.current_x = it.hpos = 0;
 20515 
 20516   /* Set the window start position here explicitly, to avoid an
 20517      infinite loop in case the functions in window-scroll-functions
 20518      get errors.  */
 20519   set_marker_both (w->start, Qnil, IT_CHARPOS (it), IT_BYTEPOS (it));
 20520 
 20521   /* Run scroll hooks.  */
 20522   startp = run_window_scroll_functions (window, it.current.pos);
 20523 
 20524   /* We invoke try_window and try_window_reusing_current_matrix below,
 20525      and they manipulate the bidi cache.  Save and restore the cache
 20526      state of our iterator, so we could continue using it after that.  */
 20527   itdata = bidi_shelve_cache ();
 20528 
 20529   /* Redisplay the window.  */
 20530   use_desired_matrix = false;
 20531   if (!current_matrix_up_to_date_p
 20532       || windows_or_buffers_changed
 20533       || f->cursor_type_changed
 20534       /* Don't use try_window_reusing_current_matrix in this case
 20535          because it can have changed the buffer.  */
 20536       || !NILP (Vwindow_scroll_functions)
 20537       || !just_this_one_p
 20538       || MINI_WINDOW_P (w)
 20539       || !(used_current_matrix_p
 20540            = try_window_reusing_current_matrix (w)))
 20541     use_desired_matrix = (try_window (window, startp, 0) == 1);
 20542 
 20543   bidi_unshelve_cache (itdata, false);
 20544 
 20545   /* If new fonts have been loaded (due to fontsets), give up.  We
 20546      have to start a new redisplay since we need to re-adjust glyph
 20547      matrices.  */
 20548   if (f->fonts_changed)
 20549     goto need_larger_matrices;
 20550 
 20551   /* If cursor did not appear assume that the middle of the window is
 20552      in the first line of the window.  Do it again with the next line.
 20553      (Imagine a window of height 100, displaying two lines of height
 20554      60.  Moving back 50 from it->last_visible_y will end in the first
 20555      line.)  */
 20556   if (w->cursor.vpos < 0)
 20557     {
 20558       if (w->window_end_valid && PT >= Z - w->window_end_pos)
 20559         {
 20560           clear_glyph_matrix (w->desired_matrix);
 20561           move_it_by_lines (&it, 1);
 20562           try_window (window, it.current.pos, 0);
 20563         }
 20564       else if (PT < IT_CHARPOS (it))
 20565         {
 20566           clear_glyph_matrix (w->desired_matrix);
 20567           move_it_by_lines (&it, -1);
 20568           try_window (window, it.current.pos, 0);
 20569         }
 20570       else if (scroll_conservatively > SCROLL_LIMIT
 20571                && (it.method == GET_FROM_STRING
 20572                    || overlay_touches_p (IT_CHARPOS (it)))
 20573                && IT_CHARPOS (it) < ZV)
 20574         {
 20575           /* If the window starts with a before-string that spans more
 20576              than one screen line, using that position to display the
 20577              window might fail to bring point into the view, because
 20578              start_display will always start by displaying the string,
 20579              whereas the code above determines where to set w->start
 20580              by the buffer position of the place where it takes screen
 20581              coordinates.  Try to recover by finding the next screen
 20582              line that displays buffer text.  */
 20583           ptrdiff_t pos0 = IT_CHARPOS (it);
 20584 
 20585           clear_glyph_matrix (w->desired_matrix);
 20586           do {
 20587             move_it_by_lines (&it, 1);
 20588           } while (IT_CHARPOS (it) == pos0);
 20589           try_window (window, it.current.pos, 0);
 20590         }
 20591       else
 20592         {
 20593           /* Not much we can do about it.  */
 20594         }
 20595     }
 20596 
 20597   /* Consider the following case: Window starts at BEGV, there is
 20598      invisible, intangible text at BEGV, so that display starts at
 20599      some point START > BEGV.  It can happen that we are called with
 20600      PT somewhere between BEGV and START.  Try to handle that case,
 20601      and similar ones.  */
 20602   if (w->cursor.vpos < 0)
 20603     {
 20604       /* Prefer the desired matrix to the current matrix, if possible,
 20605          in the fallback calculations below.  This is because using
 20606          the current matrix might completely goof, e.g. if its first
 20607          row is after point.  */
 20608       struct glyph_matrix *matrix =
 20609         use_desired_matrix ? w->desired_matrix : w->current_matrix;
 20610       /* First, try locating the proper glyph row for PT.  */
 20611       struct glyph_row *row =
 20612         row_containing_pos (w, PT, matrix->rows, NULL, 0);
 20613 
 20614       /* Sometimes point is at the beginning of invisible text that is
 20615          before the 1st character displayed in the row.  In that case,
 20616          row_containing_pos fails to find the row, because no glyphs
 20617          with appropriate buffer positions are present in the row.
 20618          Therefore, we next try to find the row which shows the 1st
 20619          position after the invisible text.  */
 20620       if (!row)
 20621         {
 20622           Lisp_Object val =
 20623             get_char_property_and_overlay (make_fixnum (PT), Qinvisible,
 20624                                            Qnil, NULL);
 20625 
 20626           if (TEXT_PROP_MEANS_INVISIBLE (val) != 0)
 20627             {
 20628               ptrdiff_t alt_pos;
 20629               Lisp_Object invis_end =
 20630                 Fnext_single_char_property_change (make_fixnum (PT), Qinvisible,
 20631                                                    Qnil, Qnil);
 20632 
 20633               if (FIXNATP (invis_end))
 20634                 alt_pos = XFIXNAT (invis_end);
 20635               else
 20636                 alt_pos = ZV;
 20637               row = row_containing_pos (w, alt_pos, matrix->rows, NULL, 0);
 20638             }
 20639         }
 20640       /* Finally, fall back on the first row of the window after the
 20641          tab-line and header line (if any).  This is slightly better
 20642          than not displaying the cursor at all.  */
 20643       if (!row)
 20644         {
 20645           row = matrix->rows;
 20646           /* Skip the tab-line and header-line rows, if any.  */
 20647           if (row->tab_line_p)
 20648             ++row;
 20649           if (row->mode_line_p)
 20650             ++row;
 20651         }
 20652       set_cursor_from_row (w, row, matrix, 0, 0, 0, 0);
 20653     }
 20654 
 20655   if (!cursor_row_fully_visible_p (w, false, false, false))
 20656     {
 20657       /* If vscroll is enabled, disable it and try again.  */
 20658       if (w->vscroll)
 20659         {
 20660           w->vscroll = 0;
 20661           clear_glyph_matrix (w->desired_matrix);
 20662           goto recenter;
 20663         }
 20664 
 20665       /* Users who set scroll-conservatively to a large number want
 20666          point just above/below the scroll margin.  If we ended up
 20667          with point's row partially visible, move the window start to
 20668          make that row fully visible and out of the margin.  */
 20669       if (scroll_conservatively > SCROLL_LIMIT)
 20670         {
 20671           int window_total_lines
 20672             = WINDOW_TOTAL_LINES (w) * FRAME_LINE_HEIGHT (f) / frame_line_height;
 20673           bool move_down = w->cursor.vpos >= window_total_lines / 2;
 20674 
 20675           move_it_by_lines (&it, move_down ? margin + 1 : -(margin + 1));
 20676           clear_glyph_matrix (w->desired_matrix);
 20677           if (1 == try_window (window, it.current.pos,
 20678                                TRY_WINDOW_CHECK_MARGINS))
 20679             goto done;
 20680         }
 20681 
 20682       /* If centering point failed to make the whole line visible,
 20683          put point at the top instead.  That has to make the whole line
 20684          visible, if it can be done.  */
 20685       if (centering_position == 0)
 20686         goto done;
 20687 
 20688       clear_glyph_matrix (w->desired_matrix);
 20689       centering_position = 0;
 20690       goto recenter;
 20691     }
 20692 
 20693  done:
 20694 
 20695   SET_TEXT_POS_FROM_MARKER (startp, w->start);
 20696   w->start_at_line_beg = (CHARPOS (startp) == BEGV
 20697                           || FETCH_BYTE (BYTEPOS (startp) - 1) == '\n');
 20698 
 20699   /* Display the mode line, header line, and tab-line, if we must.  */
 20700   if ((update_mode_line
 20701        /* If window not full width, must redo its mode line
 20702           if (a) the window to its side is being redone and
 20703           (b) we do a frame-based redisplay.  This is a consequence
 20704           of how inverted lines are drawn in frame-based redisplay.  */
 20705        || (!just_this_one_p
 20706            && !FRAME_WINDOW_P (f)
 20707            && !WINDOW_FULL_WIDTH_P (w))
 20708        /* Line number to display.  */
 20709        || w->base_line_pos > 0
 20710        /* Column number is displayed and different from the one displayed.  */
 20711        || (w->column_number_displayed != -1
 20712            && (w->column_number_displayed != current_column ())))
 20713       /* This means that the window has a mode line.  */
 20714       && (window_wants_mode_line (w)
 20715           || window_wants_header_line (w)
 20716           || window_wants_tab_line (w)))
 20717     {
 20718       specpdl_ref count1 = SPECPDL_INDEX ();
 20719 
 20720       specbind (Qinhibit_quit, Qt);
 20721       display_mode_lines (w);
 20722       unbind_to (count1, Qnil);
 20723 
 20724       /* If mode line height has changed, arrange for a thorough
 20725          immediate redisplay using the correct mode line height.  */
 20726       if (window_wants_mode_line (w)
 20727           && CURRENT_MODE_LINE_HEIGHT (w) != DESIRED_MODE_LINE_HEIGHT (w))
 20728         {
 20729           f->fonts_changed = true;
 20730           w->mode_line_height = -1;
 20731           MATRIX_MODE_LINE_ROW (w->current_matrix)->height
 20732             = DESIRED_MODE_LINE_HEIGHT (w);
 20733         }
 20734 
 20735       /* If tab line height has changed, arrange for a thorough
 20736          immediate redisplay using the correct tab line height.  */
 20737       if (window_wants_tab_line (w)
 20738           && CURRENT_TAB_LINE_HEIGHT (w) != DESIRED_TAB_LINE_HEIGHT (w))
 20739         {
 20740           f->fonts_changed = true;
 20741           w->tab_line_height = -1;
 20742           MATRIX_TAB_LINE_ROW (w->current_matrix)->height
 20743             = DESIRED_TAB_LINE_HEIGHT (w);
 20744         }
 20745 
 20746       /* If header line height has changed, arrange for a thorough
 20747          immediate redisplay using the correct header line height.  */
 20748       if (window_wants_header_line (w)
 20749           && CURRENT_HEADER_LINE_HEIGHT (w) != DESIRED_HEADER_LINE_HEIGHT (w))
 20750         {
 20751           f->fonts_changed = true;
 20752           w->header_line_height = -1;
 20753           MATRIX_HEADER_LINE_ROW (w->current_matrix)->height
 20754             = DESIRED_HEADER_LINE_HEIGHT (w);
 20755         }
 20756 
 20757       if (f->fonts_changed)
 20758         goto need_larger_matrices;
 20759     }
 20760 
 20761   if (!line_number_displayed && w->base_line_pos != -1)
 20762     {
 20763       w->base_line_pos = 0;
 20764       w->base_line_number = 0;
 20765     }
 20766 
 20767  finish_menu_bars:
 20768 
 20769   /* When we reach a frame's selected window, redo the frame's menu
 20770      bar, tool bar, tab-bar, and the frame's title.  */
 20771   if (update_mode_line
 20772       && EQ (FRAME_SELECTED_WINDOW (f), window))
 20773     {
 20774       bool redisplay_menu_p;
 20775 
 20776       if (FRAME_WINDOW_P (f))
 20777         {
 20778 #ifdef HAVE_EXT_MENU_BAR
 20779           redisplay_menu_p = FRAME_EXTERNAL_MENU_BAR (f);
 20780 #else
 20781           redisplay_menu_p = FRAME_MENU_BAR_LINES (f) > 0;
 20782 #endif
 20783         }
 20784       else
 20785         redisplay_menu_p = FRAME_MENU_BAR_LINES (f) > 0;
 20786 
 20787       if (redisplay_menu_p)
 20788         display_menu_bar (w);
 20789 
 20790 #ifdef HAVE_WINDOW_SYSTEM
 20791       if (FRAME_WINDOW_P (f))
 20792         {
 20793           if (WINDOWP (f->tab_bar_window)
 20794               && (FRAME_TAB_BAR_LINES (f) > 0
 20795                   || !NILP (Vauto_resize_tab_bars))
 20796               && redisplay_tab_bar (f))
 20797             ignore_mouse_drag_p = true;
 20798 
 20799 #ifdef HAVE_EXT_TOOL_BAR
 20800           if (FRAME_EXTERNAL_TOOL_BAR (f))
 20801             update_frame_tool_bar (f);
 20802 #else
 20803           if (WINDOWP (f->tool_bar_window)
 20804               && (FRAME_TOOL_BAR_LINES (f) > 0
 20805                   || !NILP (Vauto_resize_tool_bars))
 20806               && redisplay_tool_bar (f))
 20807             ignore_mouse_drag_p = true;
 20808 #endif
 20809         }
 20810       else
 20811         {
 20812           if ((FRAME_TAB_BAR_LINES (f) > 0))
 20813             display_tab_bar (w);
 20814         }
 20815 
 20816       gui_consider_frame_title (w->frame);
 20817 #else
 20818       if ((FRAME_TAB_BAR_LINES (f) > 0))
 20819         display_tab_bar (w);
 20820 #endif
 20821     }
 20822 
 20823 #ifdef HAVE_WINDOW_SYSTEM
 20824   if (FRAME_WINDOW_P (f)
 20825       && update_window_fringes (w, (just_this_one_p
 20826                                     || (!used_current_matrix_p && !overlay_arrow_seen)
 20827                                     || w->pseudo_window_p)))
 20828     {
 20829       update_begin (f);
 20830       block_input ();
 20831       if (draw_window_fringes (w, true))
 20832         {
 20833           if (WINDOW_RIGHT_DIVIDER_WIDTH (w))
 20834             gui_draw_right_divider (w);
 20835           else
 20836             gui_draw_vertical_border (w);
 20837         }
 20838       unblock_input ();
 20839       update_end (f);
 20840     }
 20841 
 20842   if (WINDOW_BOTTOM_DIVIDER_WIDTH (w))
 20843     gui_draw_bottom_divider (w);
 20844 #endif /* HAVE_WINDOW_SYSTEM */
 20845 
 20846   /* We go to this label, with fonts_changed set, if it is
 20847      necessary to try again using larger glyph matrices.
 20848      We have to redeem the scroll bar even in this case,
 20849      because the loop in redisplay_internal expects that.  */
 20850  need_larger_matrices:
 20851   ;
 20852  finish_scroll_bars:
 20853 
 20854    if (WINDOW_HAS_VERTICAL_SCROLL_BAR (w) || WINDOW_HAS_HORIZONTAL_SCROLL_BAR (w))
 20855     {
 20856       if (WINDOW_HAS_VERTICAL_SCROLL_BAR (w))
 20857         /* Set the thumb's position and size.  */
 20858         set_vertical_scroll_bar (w);
 20859 
 20860       if (WINDOW_HAS_HORIZONTAL_SCROLL_BAR (w))
 20861         /* Set the thumb's position and size.  */
 20862         set_horizontal_scroll_bar (w);
 20863 
 20864       /* Note that we actually used the scroll bar attached to this
 20865          window, so it shouldn't be deleted at the end of redisplay.  */
 20866       if (FRAME_TERMINAL (f)->redeem_scroll_bar_hook)
 20867         (*FRAME_TERMINAL (f)->redeem_scroll_bar_hook) (w);
 20868     }
 20869 
 20870   /* Restore current_buffer and value of point in it.  The window
 20871      update may have changed the buffer, so first make sure `opoint'
 20872      is still valid (Bug#6177).  */
 20873   if (CHARPOS (opoint) < BEGV)
 20874     TEMP_SET_PT_BOTH (BEGV, BEGV_BYTE);
 20875   else if (CHARPOS (opoint) > ZV)
 20876     TEMP_SET_PT_BOTH (Z, Z_BYTE);
 20877   else
 20878     TEMP_SET_PT_BOTH (CHARPOS (opoint), BYTEPOS (opoint));
 20879 
 20880   set_buffer_internal_1 (old);
 20881   /* Avoid an abort in TEMP_SET_PT_BOTH if the buffer has become
 20882      shorter.  This can be caused by log truncation in *Messages*.  */
 20883   if (CHARPOS (lpoint) <= ZV)
 20884     TEMP_SET_PT_BOTH (CHARPOS (lpoint), BYTEPOS (lpoint));
 20885 
 20886   unbind_to (count, Qnil);
 20887 }
 20888 
 20889 
 20890 /* Build the complete desired matrix of WINDOW with a window start
 20891    buffer position POS.
 20892 
 20893    Value is 1 if successful.  It is zero if fonts were loaded during
 20894    redisplay or the dimensions of the desired matrix were found
 20895    insufficient, which makes re-adjusting glyph matrices necessary.
 20896    Value is -1 if point would appear in the scroll margins.  (We check
 20897    the former only if TRY_WINDOW_IGNORE_FONTS_CHANGE is unset in
 20898    FLAGS, and the latter only if TRY_WINDOW_CHECK_MARGINS is set in
 20899    FLAGS.)
 20900 
 20901    Note that 'x-show-tip' invokes this function in a special way, and
 20902    in that case the return value of zero doesn't necessarily mean the
 20903    glyph matrices need to be re-adjusted, if the entire text of the
 20904    tooltip was processed and has its glyphs in the matrix's glyph
 20905    rows, i.e. if the dimensions of the matrix were found insufficient
 20906    while producing empty glyph rows beyond ZV.  */
 20907 
 20908 int
 20909 try_window (Lisp_Object window, struct text_pos pos, int flags)
 20910 {
 20911   struct window *w = XWINDOW (window);
 20912   struct it it;
 20913   struct glyph_row *last_text_row = NULL;
 20914   struct frame *f = XFRAME (w->frame);
 20915   int cursor_vpos = w->cursor.vpos;
 20916 
 20917   /* Make POS the new window start.  */
 20918   set_marker_both (w->start, Qnil, CHARPOS (pos), BYTEPOS (pos));
 20919 
 20920   /* Mark cursor position as unknown.  No overlay arrow seen.  */
 20921   w->cursor.vpos = -1;
 20922   overlay_arrow_seen = false;
 20923 
 20924   /* Initialize iterator and info to start at POS.  */
 20925   start_display (&it, w, pos);
 20926   it.glyph_row->reversed_p = false;
 20927 
 20928   /* Display all lines of W.  */
 20929   while (it.current_y < it.last_visible_y)
 20930     {
 20931       int last_row_scale = it.w->nrows_scale_factor;
 20932       int last_col_scale = it.w->ncols_scale_factor;
 20933       if (display_line (&it, cursor_vpos))
 20934         last_text_row = it.glyph_row - 1;
 20935       if (f->fonts_changed
 20936           && !((flags & TRY_WINDOW_IGNORE_FONTS_CHANGE)
 20937                /* If the matrix dimensions are insufficient, we _must_
 20938                   fail and let dispnew.c reallocate the matrix.  */
 20939                && last_row_scale == it.w->nrows_scale_factor
 20940                && last_col_scale == it.w->ncols_scale_factor))
 20941         return 0;
 20942     }
 20943 
 20944   /* Save the character position of 'it' before we call
 20945      'start_display' again.  */
 20946   ptrdiff_t it_charpos = IT_CHARPOS (it);
 20947 
 20948   /* Don't let the cursor end in the scroll margins.  However, when
 20949      the window is vscrolled, we leave it to vscroll to handle the
 20950      margins, see window_scroll_pixel_based.  */
 20951   if ((flags & TRY_WINDOW_CHECK_MARGINS)
 20952       && w->vscroll == 0
 20953       && !MINI_WINDOW_P (w))
 20954     {
 20955       int top_scroll_margin = window_scroll_margin (w, MARGIN_IN_PIXELS);
 20956       int bot_scroll_margin = top_scroll_margin;
 20957       if (window_wants_header_line (w))
 20958         top_scroll_margin += CURRENT_HEADER_LINE_HEIGHT (w);
 20959       if (window_wants_tab_line (w))
 20960         top_scroll_margin += CURRENT_TAB_LINE_HEIGHT (w);
 20961       start_display (&it, w, pos);
 20962 
 20963       if ((w->cursor.y >= 0
 20964            && w->cursor.y < top_scroll_margin
 20965            && CHARPOS (pos) > BEGV)
 20966           /* rms: considering make_cursor_line_fully_visible_p here
 20967              seems to give wrong results.  We don't want to recenter
 20968              when the last line is partly visible, we want to allow
 20969              that case to be handled in the usual way.  */
 20970           || w->cursor.y > (it.last_visible_y - partial_line_height (&it)
 20971                             - bot_scroll_margin - 1))
 20972         {
 20973           w->cursor.vpos = -1;
 20974           clear_glyph_matrix (w->desired_matrix);
 20975           return -1;
 20976         }
 20977     }
 20978 
 20979   /* If bottom moved off end of frame, change mode line percentage.  */
 20980   if (w->window_end_pos <= 0 && Z != it_charpos)
 20981     w->update_mode_line = true;
 20982 
 20983   /* Set window_end_pos to the offset of the last character displayed
 20984      on the window from the end of current_buffer.  Set
 20985      window_end_vpos to its row number.  */
 20986   if (last_text_row)
 20987     {
 20988       eassert (MATRIX_ROW_DISPLAYS_TEXT_P (last_text_row));
 20989       adjust_window_ends (w, last_text_row, false);
 20990       eassert
 20991         (MATRIX_ROW_DISPLAYS_TEXT_P (MATRIX_ROW (w->desired_matrix,
 20992                                                  w->window_end_vpos)));
 20993     }
 20994   else
 20995     {
 20996       w->window_end_bytepos = Z_BYTE - ZV_BYTE;
 20997       w->window_end_pos = Z - ZV;
 20998       w->window_end_vpos = 0;
 20999     }
 21000 
 21001   /* But that is not valid info until redisplay finishes.  */
 21002   w->window_end_valid = false;
 21003   return 1;
 21004 }
 21005 
 21006 
 21007 
 21008 /************************************************************************
 21009     Window redisplay reusing current matrix when buffer has not changed
 21010  ************************************************************************/
 21011 
 21012 /* Try redisplay of window W showing an unchanged buffer with a
 21013    different window start than the last time it was displayed by
 21014    reusing its current matrix.  Value is true if successful.
 21015    W->start is the new window start.  */
 21016 
 21017 static bool
 21018 try_window_reusing_current_matrix (struct window *w)
 21019 {
 21020   struct frame *f = XFRAME (w->frame);
 21021   struct glyph_row *bottom_row;
 21022   struct it it;
 21023   struct run run;
 21024   struct text_pos start, new_start;
 21025   int nrows_scrolled, i;
 21026   struct glyph_row *last_text_row;
 21027   struct glyph_row *last_reused_text_row;
 21028   struct glyph_row *start_row;
 21029   int start_vpos, min_y, max_y;
 21030 
 21031 #ifdef GLYPH_DEBUG
 21032   if (inhibit_try_window_reusing)
 21033     return false;
 21034 #endif
 21035 
 21036   if (/* This function doesn't handle terminal frames.  */
 21037       !FRAME_WINDOW_P (f)
 21038       /* Don't try to reuse the display if windows have been split
 21039          or such.  */
 21040       || windows_or_buffers_changed
 21041       || f->cursor_type_changed
 21042       /* This function cannot handle buffers where the overlay arrow
 21043          is shown on the fringes, because if the arrow position
 21044          changes, we cannot just reuse the current matrix.  */
 21045       || overlay_arrow_in_current_buffer_p ())
 21046     return false;
 21047 
 21048   /* Can't do this if showing trailing whitespace.  */
 21049   if (!NILP (Vshow_trailing_whitespace))
 21050     return false;
 21051 
 21052   /* If top-line visibility has changed, give up.  */
 21053   if (window_wants_tab_line (w)
 21054       != MATRIX_TAB_LINE_ROW (w->current_matrix)->mode_line_p)
 21055     return false;
 21056 
 21057   /* If top-line visibility has changed, give up.  */
 21058   if (window_wants_header_line (w)
 21059       != MATRIX_HEADER_LINE_ROW (w->current_matrix)->mode_line_p)
 21060     return false;
 21061 
 21062   /* Give up if old or new display is scrolled vertically.  We could
 21063      make this function handle this, but right now it doesn't.  */
 21064   start_row = MATRIX_FIRST_TEXT_ROW (w->current_matrix);
 21065   if (w->vscroll || MATRIX_ROW_PARTIALLY_VISIBLE_P (w, start_row))
 21066     return false;
 21067 
 21068   /* Clear the desired matrix for the display below.  */
 21069   clear_glyph_matrix (w->desired_matrix);
 21070 
 21071   /* Give up if line numbers are being displayed, because reusing the
 21072      current matrix might use the wrong width for line-number
 21073      display.  */
 21074   if (!NILP (Vdisplay_line_numbers))
 21075     return false;
 21076 
 21077   /* Can't scroll the display of w32 GUI frames when position of point
 21078      is indicated by the system caret, because scrolling the display
 21079      will then "copy" the pixels used by the caret.  */
 21080 #ifdef HAVE_NTGUI
 21081   if (w32_use_visible_system_caret)
 21082     return false;
 21083 #endif
 21084 
 21085   /* The variable new_start now holds the new window start.  The old
 21086      start `start' can be determined from the current matrix.  */
 21087   SET_TEXT_POS_FROM_MARKER (new_start, w->start);
 21088   start = start_row->minpos;
 21089   start_vpos = MATRIX_ROW_VPOS (start_row, w->current_matrix);
 21090 
 21091   if (CHARPOS (new_start) <= CHARPOS (start))
 21092     {
 21093       /* Don't use this method if the display starts with an ellipsis
 21094          displayed for invisible text.  It's not easy to handle that case
 21095          below, and it's certainly not worth the effort since this is
 21096          not a frequent case.  */
 21097       if (in_ellipses_for_invisible_text_p (&start_row->start, w))
 21098         return false;
 21099 
 21100       IF_DEBUG (debug_method_add (w, "twu1"));
 21101 
 21102       /* Display up to a row that can be reused.  The variable
 21103          last_text_row is set to the last row displayed that displays
 21104          text.  Note that it.vpos == 0 if or if not there is a
 21105          header-line; it's not the same as the MATRIX_ROW_VPOS!  */
 21106       start_display (&it, w, new_start);
 21107       w->cursor.vpos = -1;
 21108       last_text_row = last_reused_text_row = NULL;
 21109 
 21110       while (it.current_y < it.last_visible_y && !f->fonts_changed)
 21111         {
 21112           /* If we have reached into the characters in the START row,
 21113              that means the line boundaries have changed.  So we
 21114              can't start copying with the row START.  Maybe it will
 21115              work to start copying with the following row.  */
 21116           while (IT_CHARPOS (it) > CHARPOS (start))
 21117             {
 21118               /* Advance to the next row as the "start".  */
 21119               start_row++;
 21120               start = start_row->minpos;
 21121               /* If there are no more rows to try, or just one, give up.  */
 21122               if (start_row == MATRIX_MODE_LINE_ROW (w->current_matrix) - 1
 21123                   || w->vscroll || MATRIX_ROW_PARTIALLY_VISIBLE_P (w, start_row)
 21124                   || CHARPOS (start) == ZV)
 21125                 {
 21126                   clear_glyph_matrix (w->desired_matrix);
 21127                   return false;
 21128                 }
 21129 
 21130               start_vpos = MATRIX_ROW_VPOS (start_row, w->current_matrix);
 21131             }
 21132           /* If we have reached alignment, we can copy the rest of the
 21133              rows.  */
 21134           if (IT_CHARPOS (it) == CHARPOS (start)
 21135               /* Don't accept "alignment" inside a display vector,
 21136                  since start_row could have started in the middle of
 21137                  that same display vector (thus their character
 21138                  positions match), and we have no way of telling if
 21139                  that is the case.  */
 21140               && it.current.dpvec_index < 0)
 21141             break;
 21142 
 21143           it.glyph_row->reversed_p = false;
 21144           if (display_line (&it, -1))
 21145             last_text_row = it.glyph_row - 1;
 21146 
 21147         }
 21148 
 21149       /* A value of current_y < last_visible_y means that we stopped
 21150          at the previous window start, which in turn means that we
 21151          have at least one reusable row.  */
 21152       if (it.current_y < it.last_visible_y)
 21153         {
 21154           struct glyph_row *row;
 21155 
 21156           /* IT.vpos always starts from 0; it counts text lines.  */
 21157           nrows_scrolled = it.vpos - (start_row - MATRIX_FIRST_TEXT_ROW (w->current_matrix));
 21158 
 21159           /* Find PT if not already found in the lines displayed.  */
 21160           if (w->cursor.vpos < 0)
 21161             {
 21162               int dy = it.current_y - start_row->y;
 21163 
 21164               row = MATRIX_FIRST_TEXT_ROW (w->current_matrix);
 21165               row = row_containing_pos (w, PT, row, NULL, dy);
 21166               if (row)
 21167                 set_cursor_from_row (w, row, w->current_matrix, 0, 0,
 21168                                      dy, nrows_scrolled);
 21169               else
 21170                 {
 21171                   clear_glyph_matrix (w->desired_matrix);
 21172                   return false;
 21173                 }
 21174             }
 21175 
 21176           /* Scroll the display.  Do it before the current matrix is
 21177              changed.  The problem here is that update has not yet
 21178              run, i.e. part of the current matrix is not up to date.
 21179              scroll_run_hook will clear the cursor, and use the
 21180              current matrix to get the height of the row the cursor is
 21181              in.  */
 21182           run.current_y = start_row->y;
 21183           run.desired_y = it.current_y;
 21184           run.height = it.last_visible_y - it.current_y;
 21185 
 21186           if (run.height > 0 && run.current_y != run.desired_y)
 21187             {
 21188 #ifdef HAVE_WINDOW_SYSTEM
 21189               update_begin (f);
 21190               gui_update_window_begin (w);
 21191               FRAME_RIF (f)->clear_window_mouse_face (w);
 21192               FRAME_RIF (f)->scroll_run_hook (w, &run);
 21193               gui_update_window_end (w, false, false);
 21194               update_end (f);
 21195 #endif
 21196             }
 21197 
 21198           /* Shift current matrix down by nrows_scrolled lines.  */
 21199           bottom_row = MATRIX_BOTTOM_TEXT_ROW (w->current_matrix, w);
 21200           rotate_matrix (w->current_matrix,
 21201                          start_vpos,
 21202                          MATRIX_ROW_VPOS (bottom_row, w->current_matrix),
 21203                          nrows_scrolled);
 21204 
 21205           /* Disable lines that must be updated.  */
 21206           for (i = 0; i < nrows_scrolled; ++i)
 21207             (start_row + i)->enabled_p = false;
 21208 
 21209           /* Re-compute Y positions.  */
 21210           min_y = WINDOW_TAB_LINE_HEIGHT (w) + WINDOW_HEADER_LINE_HEIGHT (w);
 21211           max_y = it.last_visible_y;
 21212           for (row = start_row + nrows_scrolled;
 21213                row < bottom_row;
 21214                ++row)
 21215             {
 21216               row->y = it.current_y;
 21217               row->visible_height = row->height;
 21218 
 21219               if (row->y < min_y)
 21220                 row->visible_height -= min_y - row->y;
 21221               if (row->y + row->height > max_y)
 21222                 row->visible_height -= row->y + row->height - max_y;
 21223               if (row->fringe_bitmap_periodic_p)
 21224                 row->redraw_fringe_bitmaps_p = true;
 21225 
 21226               it.current_y += row->height;
 21227 
 21228               if (MATRIX_ROW_DISPLAYS_TEXT_P (row))
 21229                 last_reused_text_row = row;
 21230               if (MATRIX_ROW_BOTTOM_Y (row) >= it.last_visible_y)
 21231                 break;
 21232             }
 21233 
 21234           /* Disable lines in the current matrix which are now
 21235              below the window.  */
 21236           for (++row; row < bottom_row; ++row)
 21237             row->enabled_p = row->mode_line_p = row->tab_line_p = false;
 21238         }
 21239 
 21240       /* Update window_end_pos etc.; last_reused_text_row is the last
 21241          reused row from the current matrix containing text, if any.
 21242          The value of last_text_row is the last displayed line
 21243          containing text.  */
 21244       if (last_reused_text_row)
 21245         adjust_window_ends (w, last_reused_text_row, true);
 21246       else if (last_text_row)
 21247         adjust_window_ends (w, last_text_row, false);
 21248       else
 21249         {
 21250           /* This window must be completely empty.  */
 21251           w->window_end_bytepos = Z_BYTE - ZV_BYTE;
 21252           w->window_end_pos = Z - ZV;
 21253           w->window_end_vpos = 0;
 21254         }
 21255       w->window_end_valid = false;
 21256 
 21257       /* Update hint: don't try scrolling again in update_window.  */
 21258       w->desired_matrix->no_scrolling_p = true;
 21259 
 21260 #ifdef GLYPH_DEBUG
 21261       debug_method_add (w, "try_window_reusing_current_matrix 1");
 21262 #endif
 21263       return true;
 21264     }
 21265   else if (CHARPOS (new_start) > CHARPOS (start))
 21266     {
 21267       struct glyph_row *pt_row, *row;
 21268       struct glyph_row *first_reusable_row;
 21269       struct glyph_row *first_row_to_display;
 21270       int dy;
 21271       int yb = window_text_bottom_y (w);
 21272 
 21273       /* Find the row starting at new_start, if there is one.  Don't
 21274          reuse a partially visible line at the end.  */
 21275       first_reusable_row = start_row;
 21276       while (first_reusable_row->enabled_p
 21277              && MATRIX_ROW_BOTTOM_Y (first_reusable_row) < yb
 21278              && (MATRIX_ROW_START_CHARPOS (first_reusable_row)
 21279                  < CHARPOS (new_start)))
 21280         ++first_reusable_row;
 21281 
 21282       /* Give up if there is no row to reuse.  */
 21283       if (MATRIX_ROW_BOTTOM_Y (first_reusable_row) >= yb
 21284           || !first_reusable_row->enabled_p
 21285           || (MATRIX_ROW_START_CHARPOS (first_reusable_row)
 21286               != CHARPOS (new_start)))
 21287         return false;
 21288 
 21289       /* We can reuse fully visible rows beginning with
 21290          first_reusable_row to the end of the window.  Set
 21291          first_row_to_display to the first row that cannot be reused.
 21292          Set pt_row to the row containing point, if there is any.  */
 21293       pt_row = NULL;
 21294       for (first_row_to_display = first_reusable_row;
 21295            MATRIX_ROW_BOTTOM_Y (first_row_to_display) < yb;
 21296            ++first_row_to_display)
 21297         {
 21298           if (PT >= MATRIX_ROW_START_CHARPOS (first_row_to_display)
 21299               && (PT < MATRIX_ROW_END_CHARPOS (first_row_to_display)
 21300                   || (PT == MATRIX_ROW_END_CHARPOS (first_row_to_display)
 21301                       && first_row_to_display->ends_at_zv_p
 21302                       && pt_row == NULL)))
 21303             pt_row = first_row_to_display;
 21304         }
 21305 
 21306       if (first_row_to_display->y >= yb)
 21307         return false;
 21308 
 21309       /* Start displaying at the start of first_row_to_display.  */
 21310       init_to_row_start (&it, w, first_row_to_display);
 21311 
 21312       nrows_scrolled = (MATRIX_ROW_VPOS (first_reusable_row, w->current_matrix)
 21313                         - start_vpos);
 21314       it.vpos = (MATRIX_ROW_VPOS (first_row_to_display, w->current_matrix)
 21315                  - nrows_scrolled);
 21316       it.current_y = (first_row_to_display->y - first_reusable_row->y
 21317                       + WINDOW_TAB_LINE_HEIGHT (w) + WINDOW_HEADER_LINE_HEIGHT (w));
 21318 
 21319       /* Display lines beginning with first_row_to_display in the
 21320          desired matrix.  Set last_text_row to the last row displayed
 21321          that displays text.  */
 21322       it.glyph_row = MATRIX_ROW (w->desired_matrix, it.vpos);
 21323       if (pt_row == NULL)
 21324         w->cursor.vpos = -1;
 21325       last_text_row = NULL;
 21326       while (it.current_y < it.last_visible_y && !f->fonts_changed)
 21327         if (display_line (&it, w->cursor.vpos))
 21328           last_text_row = it.glyph_row - 1;
 21329 
 21330       /* If point is in a reused row, adjust y and vpos of the cursor
 21331          position.  */
 21332       if (pt_row)
 21333         {
 21334           w->cursor.vpos -= nrows_scrolled;
 21335           w->cursor.y -= first_reusable_row->y - start_row->y;
 21336         }
 21337 
 21338       /* Give up if point isn't in a row displayed or reused.  (This
 21339          also handles the case where w->cursor.vpos < nrows_scrolled
 21340          after the calls to display_line, which can happen with scroll
 21341          margins.  See bug#1295.)  */
 21342       if (w->cursor.vpos < 0)
 21343         {
 21344           clear_glyph_matrix (w->desired_matrix);
 21345           return false;
 21346         }
 21347 
 21348       /* Scroll the display.  */
 21349       run.current_y = first_reusable_row->y;
 21350       run.desired_y = WINDOW_TAB_LINE_HEIGHT (w) + WINDOW_HEADER_LINE_HEIGHT (w);
 21351       run.height = it.last_visible_y - run.current_y;
 21352       dy = run.current_y - run.desired_y;
 21353 
 21354       if (run.height)
 21355         {
 21356 #ifdef HAVE_WINDOW_SYSTEM
 21357           update_begin (f);
 21358           gui_update_window_begin (w);
 21359           FRAME_RIF (f)->clear_window_mouse_face (w);
 21360           FRAME_RIF (f)->scroll_run_hook (w, &run);
 21361           gui_update_window_end (w, false, false);
 21362           update_end (f);
 21363 #endif
 21364         }
 21365 
 21366       /* Adjust Y positions of reused rows.  */
 21367       bottom_row = MATRIX_BOTTOM_TEXT_ROW (w->current_matrix, w);
 21368       min_y = WINDOW_TAB_LINE_HEIGHT (w) + WINDOW_HEADER_LINE_HEIGHT (w);
 21369       max_y = it.last_visible_y;
 21370       for (row = first_reusable_row; row < first_row_to_display; ++row)
 21371         {
 21372           row->y -= dy;
 21373           row->visible_height = row->height;
 21374           if (row->y < min_y)
 21375             row->visible_height -= min_y - row->y;
 21376           if (row->y + row->height > max_y)
 21377             row->visible_height -= row->y + row->height - max_y;
 21378           if (row->fringe_bitmap_periodic_p)
 21379             row->redraw_fringe_bitmaps_p = true;
 21380         }
 21381 
 21382       /* Scroll the current matrix.  */
 21383       eassert (nrows_scrolled > 0);
 21384       rotate_matrix (w->current_matrix,
 21385                      start_vpos,
 21386                      MATRIX_ROW_VPOS (bottom_row, w->current_matrix),
 21387                      -nrows_scrolled);
 21388 
 21389       /* Disable rows not reused.  */
 21390       for (row -= nrows_scrolled; row < bottom_row; ++row)
 21391         row->enabled_p = false;
 21392 
 21393       /* Point may have moved to a different line, so we cannot assume that
 21394          the previous cursor position is valid; locate the correct row.  */
 21395       if (pt_row)
 21396         {
 21397           for (row = MATRIX_ROW (w->current_matrix, w->cursor.vpos);
 21398                row < bottom_row
 21399                  && PT >= MATRIX_ROW_END_CHARPOS (row)
 21400                  && !row->ends_at_zv_p;
 21401                row++)
 21402             {
 21403               w->cursor.vpos++;
 21404               w->cursor.y = row->y;
 21405             }
 21406           if (row < bottom_row)
 21407             {
 21408               /* Can't simply scan the row for point with
 21409                  bidi-reordered glyph rows.  Let set_cursor_from_row
 21410                  figure out where to put the cursor, and if it fails,
 21411                  give up.  */
 21412               if (!NILP (BVAR (XBUFFER (w->contents), bidi_display_reordering)))
 21413                 {
 21414                   if (!set_cursor_from_row (w, row, w->current_matrix,
 21415                                             0, 0, 0, 0))
 21416                     {
 21417                       clear_glyph_matrix (w->desired_matrix);
 21418                       return false;
 21419                     }
 21420                 }
 21421               else
 21422                 {
 21423                   struct glyph *glyph = row->glyphs[TEXT_AREA] + w->cursor.hpos;
 21424                   struct glyph *end = row->glyphs[TEXT_AREA] + row->used[TEXT_AREA];
 21425 
 21426                   for (; glyph < end
 21427                          && (!BUFFERP (glyph->object)
 21428                              || glyph->charpos < PT);
 21429                        glyph++)
 21430                     {
 21431                       w->cursor.hpos++;
 21432                       w->cursor.x += glyph->pixel_width;
 21433                     }
 21434                 }
 21435             }
 21436         }
 21437 
 21438       /* Adjust window end.  A null value of last_text_row means that
 21439          the window end is in reused rows which in turn means that
 21440          only its vpos can have changed.  */
 21441       if (last_text_row)
 21442         adjust_window_ends (w, last_text_row, false);
 21443       else
 21444         w->window_end_vpos -= nrows_scrolled;
 21445 
 21446       w->window_end_valid = false;
 21447       w->desired_matrix->no_scrolling_p = true;
 21448 
 21449 #ifdef GLYPH_DEBUG
 21450       debug_method_add (w, "try_window_reusing_current_matrix 2");
 21451 #endif
 21452       return true;
 21453     }
 21454 
 21455   return false;
 21456 }
 21457 
 21458 
 21459 
 21460 /************************************************************************
 21461    Window redisplay reusing current matrix when buffer has changed
 21462  ************************************************************************/
 21463 
 21464 static struct glyph_row *find_last_unchanged_at_beg_row (struct window *);
 21465 static struct glyph_row *find_first_unchanged_at_end_row (struct window *,
 21466                                                           ptrdiff_t *, ptrdiff_t *);
 21467 static struct glyph_row *
 21468 find_last_row_displaying_text (struct glyph_matrix *, struct it *,
 21469                                struct glyph_row *);
 21470 
 21471 
 21472 /* Return the last row in MATRIX displaying text.  If row START is
 21473    non-null, start searching with that row.  IT gives the dimensions
 21474    of the display.  Value is null if matrix is empty; otherwise it is
 21475    a pointer to the row found.  */
 21476 
 21477 static struct glyph_row *
 21478 find_last_row_displaying_text (struct glyph_matrix *matrix, struct it *it,
 21479                                struct glyph_row *start)
 21480 {
 21481   struct glyph_row *row, *row_found;
 21482 
 21483   /* Set row_found to the last row in IT->w's current matrix
 21484      displaying text.  The loop looks funny but think of partially
 21485      visible lines.  */
 21486   row_found = NULL;
 21487   row = start ? start : MATRIX_FIRST_TEXT_ROW (matrix);
 21488   while (MATRIX_ROW_DISPLAYS_TEXT_P (row))
 21489     {
 21490       eassert (row->enabled_p);
 21491       row_found = row;
 21492       if (MATRIX_ROW_BOTTOM_Y (row) >= it->last_visible_y)
 21493         break;
 21494       ++row;
 21495     }
 21496 
 21497   return row_found;
 21498 }
 21499 
 21500 
 21501 /* Return the last row in the current matrix of W that is not affected
 21502    by changes at the start of current_buffer that occurred since W's
 21503    current matrix was built.  Value is null if no such row exists.
 21504 
 21505    BEG_UNCHANGED is the number of characters unchanged at the start of
 21506    current_buffer.  BEG + BEG_UNCHANGED is the buffer position of the
 21507    first changed character in current_buffer.  Characters at positions <
 21508    BEG + BEG_UNCHANGED are at the same buffer positions as they were
 21509    when the current matrix was built.  */
 21510 
 21511 static struct glyph_row *
 21512 find_last_unchanged_at_beg_row (struct window *w)
 21513 {
 21514   ptrdiff_t first_changed_pos = BEG + BEG_UNCHANGED;
 21515   struct glyph_row *row;
 21516   struct glyph_row *row_found = NULL;
 21517   int yb = window_text_bottom_y (w);
 21518 
 21519   /* Find the last row displaying unchanged text.  */
 21520   for (row = MATRIX_FIRST_TEXT_ROW (w->current_matrix);
 21521        MATRIX_ROW_DISPLAYS_TEXT_P (row)
 21522          && MATRIX_ROW_START_CHARPOS (row) < first_changed_pos;
 21523        ++row)
 21524     {
 21525       if (/* If row ends before first_changed_pos, it is unchanged,
 21526              except in some case.  */
 21527           MATRIX_ROW_END_CHARPOS (row) <= first_changed_pos
 21528           /* When row ends in ZV and we write at ZV it is not
 21529              unchanged.  */
 21530           && !row->ends_at_zv_p
 21531           /* When first_changed_pos is the end of a continued line,
 21532              row is not unchanged because it may be no longer
 21533              continued.  */
 21534           && !(MATRIX_ROW_END_CHARPOS (row) == first_changed_pos
 21535                && (row->continued_p
 21536                    || row->exact_window_width_line_p))
 21537           /* If ROW->end is beyond ZV, then ROW->end is outdated and
 21538              needs to be recomputed, so don't consider this row as
 21539              unchanged.  This happens when the last line was
 21540              bidi-reordered and was killed immediately before this
 21541              redisplay cycle.  In that case, ROW->end stores the
 21542              buffer position of the first visual-order character of
 21543              the killed text, which is now beyond ZV.  */
 21544           && CHARPOS (row->end.pos) <= ZV)
 21545         row_found = row;
 21546 
 21547       /* Stop if last visible row.  */
 21548       if (MATRIX_ROW_BOTTOM_Y (row) >= yb)
 21549         break;
 21550     }
 21551 
 21552   return row_found;
 21553 }
 21554 
 21555 
 21556 /* Find the first glyph row in the current matrix of W that is not
 21557    affected by changes at the end of current_buffer since the
 21558    time W's current matrix was built.
 21559 
 21560    Return in *DELTA the number of chars by which buffer positions in
 21561    unchanged text at the end of current_buffer must be adjusted.
 21562 
 21563    Return in *DELTA_BYTES the corresponding number of bytes.
 21564 
 21565    Value is null if no such row exists, i.e. all rows are affected by
 21566    changes.  */
 21567 
 21568 static struct glyph_row *
 21569 find_first_unchanged_at_end_row (struct window *w,
 21570                                  ptrdiff_t *delta, ptrdiff_t *delta_bytes)
 21571 {
 21572   struct glyph_row *row;
 21573   struct glyph_row *row_found = NULL;
 21574 
 21575   *delta = *delta_bytes = 0;
 21576 
 21577   /* Display must not have been paused, otherwise the current matrix
 21578      is not up to date.  */
 21579   eassert (w->window_end_valid);
 21580 
 21581   /* A value of window_end_pos >= END_UNCHANGED means that the window
 21582      end is in the range of changed text.  If so, there is no
 21583      unchanged row at the end of W's current matrix.  */
 21584   if (w->window_end_pos >= END_UNCHANGED)
 21585     return NULL;
 21586 
 21587   /* Set row to the last row in W's current matrix displaying text.  */
 21588   row = MATRIX_ROW (w->current_matrix, w->window_end_vpos);
 21589 
 21590   /* If matrix is entirely empty, no unchanged row exists.  */
 21591   if (MATRIX_ROW_DISPLAYS_TEXT_P (row))
 21592     {
 21593       /* The value of row is the last glyph row in the matrix having a
 21594          meaningful buffer position in it.  The end position of row
 21595          corresponds to window_end_pos.  This allows us to translate
 21596          buffer positions in the current matrix to current buffer
 21597          positions for characters not in changed text.  */
 21598       ptrdiff_t Z_old =
 21599         MATRIX_ROW_END_CHARPOS (row) + w->window_end_pos;
 21600       ptrdiff_t Z_BYTE_old =
 21601         MATRIX_ROW_END_BYTEPOS (row) + w->window_end_bytepos;
 21602       ptrdiff_t last_unchanged_pos, last_unchanged_pos_old;
 21603       struct glyph_row *first_text_row
 21604         = MATRIX_FIRST_TEXT_ROW (w->current_matrix);
 21605 
 21606       *delta = Z - Z_old;
 21607       *delta_bytes = Z_BYTE - Z_BYTE_old;
 21608 
 21609       /* Set last_unchanged_pos to the buffer position of the last
 21610          character in the buffer that has not been changed.  Z is the
 21611          index + 1 of the last character in current_buffer, i.e. by
 21612          subtracting END_UNCHANGED we get the index of the last
 21613          unchanged character, and we have to add BEG to get its buffer
 21614          position.  */
 21615       last_unchanged_pos = Z - END_UNCHANGED + BEG;
 21616       last_unchanged_pos_old = last_unchanged_pos - *delta;
 21617 
 21618       /* Search backward from ROW for a row displaying a line that
 21619          starts at a minimum position >= last_unchanged_pos_old.  */
 21620       for (; row > first_text_row; --row)
 21621         {
 21622           /* This used to abort, but it can happen.
 21623              It is ok to just stop the search instead here.  KFS.  */
 21624           if (!row->enabled_p || !MATRIX_ROW_DISPLAYS_TEXT_P (row))
 21625             break;
 21626 
 21627           if (MATRIX_ROW_START_CHARPOS (row) >= last_unchanged_pos_old)
 21628             row_found = row;
 21629         }
 21630     }
 21631 
 21632   eassert (!row_found || MATRIX_ROW_DISPLAYS_TEXT_P (row_found));
 21633 
 21634   return row_found;
 21635 }
 21636 
 21637 
 21638 /* Make sure that glyph rows in the current matrix of window W
 21639    reference the same glyph memory as corresponding rows in the
 21640    frame's frame matrix.  This function is called after scrolling W's
 21641    current matrix on a terminal frame in try_window_id and
 21642    try_window_reusing_current_matrix.  */
 21643 
 21644 static void
 21645 sync_frame_with_window_matrix_rows (struct window *w)
 21646 {
 21647   struct frame *f = XFRAME (w->frame);
 21648   struct glyph_row *window_row, *window_row_end, *frame_row;
 21649 
 21650   /* Preconditions: W must be a leaf window and full-width.  Its frame
 21651      must have a frame matrix.  */
 21652   eassert (BUFFERP (w->contents));
 21653   eassert (WINDOW_FULL_WIDTH_P (w));
 21654   eassert (!FRAME_WINDOW_P (f));
 21655 
 21656   /* If W is a full-width window, glyph pointers in W's current matrix
 21657      have, by definition, to be the same as glyph pointers in the
 21658      corresponding frame matrix.  Note that frame matrices have no
 21659      marginal areas (see build_frame_matrix).  */
 21660   window_row = w->current_matrix->rows;
 21661   window_row_end = window_row + w->current_matrix->nrows;
 21662   frame_row = f->current_matrix->rows + WINDOW_TOP_EDGE_LINE (w);
 21663   while (window_row < window_row_end)
 21664     {
 21665       struct glyph *start = window_row->glyphs[LEFT_MARGIN_AREA];
 21666       struct glyph *end = window_row->glyphs[LAST_AREA];
 21667 
 21668       frame_row->glyphs[LEFT_MARGIN_AREA] = start;
 21669       frame_row->glyphs[TEXT_AREA] = start;
 21670       frame_row->glyphs[RIGHT_MARGIN_AREA] = end;
 21671       frame_row->glyphs[LAST_AREA] = end;
 21672 
 21673       /* Disable frame rows whose corresponding window rows have
 21674          been disabled in try_window_id.  */
 21675       if (!window_row->enabled_p)
 21676         frame_row->enabled_p = false;
 21677 
 21678       ++window_row, ++frame_row;
 21679     }
 21680 }
 21681 
 21682 
 21683 /* Find the glyph row in window W containing CHARPOS.  Consider all
 21684    rows between START and END (not inclusive).  END null means search
 21685    all rows to the end of the display area of W.  Value is the row
 21686    containing CHARPOS or null.  */
 21687 
 21688 struct glyph_row *
 21689 row_containing_pos (struct window *w, ptrdiff_t charpos,
 21690                     struct glyph_row *start, struct glyph_row *end, int dy)
 21691 {
 21692   struct glyph_row *row = start;
 21693   struct glyph_row *best_row = NULL;
 21694   ptrdiff_t mindif = BUF_ZV (XBUFFER (w->contents)) + 1;
 21695   int last_y;
 21696 
 21697   /* If we happen to start on a header-line or a tab-line, skip that.  */
 21698   if (row->tab_line_p)
 21699     ++row;
 21700   if (row->mode_line_p)
 21701     ++row;
 21702 
 21703   if ((end && row >= end) || !row->enabled_p)
 21704     return NULL;
 21705 
 21706   last_y = window_text_bottom_y (w) - dy;
 21707 
 21708   while (true)
 21709     {
 21710       /* Give up if we have gone too far.  */
 21711       if ((end && row >= end) || !row->enabled_p)
 21712         return NULL;
 21713       /* This formerly returned if they were equal.
 21714          I think that both quantities are of a "last plus one" type;
 21715          if so, when they are equal, the row is within the screen. -- rms.  */
 21716       if (MATRIX_ROW_BOTTOM_Y (row) > last_y)
 21717         return NULL;
 21718 
 21719       /* If it is in this row, return this row.  */
 21720       if (! (MATRIX_ROW_END_CHARPOS (row) < charpos
 21721              || (MATRIX_ROW_END_CHARPOS (row) == charpos
 21722                  /* The end position of a row equals the start
 21723                     position of the next row.  If CHARPOS is there, we
 21724                     would rather consider it displayed in the next
 21725                     line, except when this line ends in ZV.  */
 21726                  && !row_for_charpos_p (row, charpos)))
 21727           && charpos >= MATRIX_ROW_START_CHARPOS (row))
 21728         {
 21729           struct glyph *g;
 21730 
 21731           if (NILP (BVAR (XBUFFER (w->contents), bidi_display_reordering))
 21732               || (!best_row && !row->continued_p))
 21733             return row;
 21734           /* In bidi-reordered rows, there could be several rows whose
 21735              edges surround CHARPOS, all of these rows belonging to
 21736              the same continued line.  We need to find the row which
 21737              fits CHARPOS the best.  */
 21738           for (g = row->glyphs[TEXT_AREA];
 21739                g < row->glyphs[TEXT_AREA] + row->used[TEXT_AREA];
 21740                g++)
 21741             {
 21742               if (!STRINGP (g->object))
 21743                 {
 21744                   if (g->charpos > 0 && eabs (g->charpos - charpos) < mindif)
 21745                     {
 21746                       mindif = eabs (g->charpos - charpos);
 21747                       best_row = row;
 21748                       /* Exact match always wins.  */
 21749                       if (mindif == 0)
 21750                         return best_row;
 21751                     }
 21752                 }
 21753             }
 21754         }
 21755       else if (best_row && !row->continued_p)
 21756         return best_row;
 21757       ++row;
 21758     }
 21759 }
 21760 
 21761 
 21762 /* Try to redisplay window W by reusing its existing display.  W's
 21763    current matrix must be up to date when this function is called,
 21764    i.e., window_end_valid must be true.
 21765 
 21766    Value is
 21767 
 21768    >= 1 if successful, i.e. display has been updated
 21769          specifically:
 21770          1 means the changes were in front of a newline that precedes
 21771            the window start, and the whole current matrix was reused
 21772          2 means the changes were after the last position displayed
 21773            in the window, and the whole current matrix was reused
 21774          3 means portions of the current matrix were reused, while
 21775            some of the screen lines were redrawn
 21776    -1   if redisplay with same window start is known not to succeed
 21777    0    if otherwise unsuccessful
 21778 
 21779    The following steps are performed:
 21780 
 21781    1. Find the last row in the current matrix of W that is not
 21782    affected by changes at the start of current_buffer.  If no such row
 21783    is found, give up.
 21784 
 21785    2. Find the first row in W's current matrix that is not affected by
 21786    changes at the end of current_buffer.  Maybe there is no such row.
 21787 
 21788    3. Display lines beginning with the row + 1 found in step 1 to the
 21789    row found in step 2 or, if step 2 didn't find a row, to the end of
 21790    the window.
 21791 
 21792    4. If cursor is not known to appear on the window, give up.
 21793 
 21794    5. If display stopped at the row found in step 2, scroll the
 21795    display and current matrix as needed.
 21796 
 21797    6. Maybe display some lines at the end of W, if we must.  This can
 21798    happen under various circumstances, like a partially visible line
 21799    becoming fully visible, or because newly displayed lines are displayed
 21800    in smaller font sizes.
 21801 
 21802    7. Update W's window end information.  */
 21803 
 21804 static int
 21805 try_window_id (struct window *w)
 21806 {
 21807   struct frame *f = XFRAME (w->frame);
 21808   struct glyph_matrix *current_matrix = w->current_matrix;
 21809   struct glyph_matrix *desired_matrix = w->desired_matrix;
 21810   struct glyph_row *last_unchanged_at_beg_row;
 21811   struct glyph_row *first_unchanged_at_end_row;
 21812   struct glyph_row *row;
 21813   struct glyph_row *bottom_row;
 21814   int bottom_vpos;
 21815   struct it it;
 21816   ptrdiff_t delta = 0, delta_bytes = 0, stop_pos;
 21817   int dvpos, dy;
 21818   struct text_pos start_pos;
 21819   struct run run;
 21820   int first_unchanged_at_end_vpos = 0;
 21821   struct glyph_row *last_text_row, *last_text_row_at_end;
 21822   struct text_pos start;
 21823   ptrdiff_t first_changed_charpos, last_changed_charpos;
 21824 
 21825 #ifdef GLYPH_DEBUG
 21826   if (inhibit_try_window_id)
 21827     return 0;
 21828 #endif
 21829 
 21830   /* This is handy for debugging.  */
 21831 #if false
 21832 #define GIVE_UP(X)                                              \
 21833   do {                                                          \
 21834     redisplay_trace ("try_window_id give up %d\n", X);          \
 21835     return 0;                                                   \
 21836   } while (false)
 21837 #else
 21838 #define GIVE_UP(X) return 0
 21839 #endif
 21840 
 21841   SET_TEXT_POS_FROM_MARKER (start, w->start);
 21842 
 21843   /* Don't use this for mini-windows because these can show
 21844      messages and mini-buffers, and we don't handle that here.  */
 21845   if (MINI_WINDOW_P (w))
 21846     GIVE_UP (1);
 21847 
 21848   /* This flag is used to prevent redisplay optimizations.  */
 21849   if (windows_or_buffers_changed || f->cursor_type_changed)
 21850     GIVE_UP (2);
 21851 
 21852   /* This function's optimizations cannot be used if overlays have
 21853      changed in the buffer displayed by the window, so give up if they
 21854      have.  */
 21855   if (w->last_overlay_modified != OVERLAY_MODIFF)
 21856     GIVE_UP (200);
 21857 
 21858   /* Verify that narrowing has not changed.
 21859      Also verify that we were not told to prevent redisplay optimizations.
 21860      It would be nice to further
 21861      reduce the number of cases where this prevents try_window_id.  */
 21862   if (current_buffer->clip_changed
 21863       || current_buffer->prevent_redisplay_optimizations_p)
 21864     GIVE_UP (3);
 21865 
 21866   /* Window must either use window-based redisplay or be full width.  */
 21867   if (!FRAME_WINDOW_P (f)
 21868       && (!FRAME_LINE_INS_DEL_OK (f)
 21869           || !WINDOW_FULL_WIDTH_P (w)))
 21870     GIVE_UP (4);
 21871 
 21872   /* Give up if point is known NOT to appear in W.  */
 21873   if (PT < CHARPOS (start))
 21874     GIVE_UP (5);
 21875 
 21876   /* Another way to prevent redisplay optimizations.  */
 21877   if (w->last_modified == 0)
 21878     GIVE_UP (6);
 21879 
 21880   /* Verify that window is not hscrolled.  */
 21881   if (w->hscroll != 0)
 21882     GIVE_UP (7);
 21883 
 21884   /* Verify that display wasn't paused.  */
 21885   if (!w->window_end_valid)
 21886     GIVE_UP (8);
 21887 
 21888   /* Likewise if highlighting trailing whitespace.  */
 21889   if (!NILP (Vshow_trailing_whitespace))
 21890     GIVE_UP (11);
 21891 
 21892   /* Can't use this if overlay arrow position and/or string have
 21893      changed.  */
 21894   if (overlay_arrows_changed_p (false))
 21895     GIVE_UP (12);
 21896 
 21897   /* When word-wrap is on, adding a space to the first word of a
 21898      wrapped line can change the wrap position, altering the line
 21899      above it.  It might be worthwhile to handle this more
 21900      intelligently, but for now just redisplay from scratch.  */
 21901   if (!NILP (BVAR (XBUFFER (w->contents), word_wrap)))
 21902     GIVE_UP (21);
 21903 
 21904   /* Under bidi reordering, adding or deleting a character in the
 21905      beginning of a paragraph, before the first strong directional
 21906      character, can change the base direction of the paragraph (unless
 21907      the buffer specifies a fixed paragraph direction), which will
 21908      require redisplaying the whole paragraph.  It might be worthwhile
 21909      to find the paragraph limits and widen the range of redisplayed
 21910      lines to that, but for now just give up this optimization and
 21911      redisplay from scratch.  */
 21912   if (!NILP (BVAR (XBUFFER (w->contents), bidi_display_reordering))
 21913       && NILP (BVAR (XBUFFER (w->contents), bidi_paragraph_direction)))
 21914     GIVE_UP (22);
 21915 
 21916   /* Give up if the buffer has line-spacing set, as Lisp-level changes
 21917      to that variable require thorough redisplay.  */
 21918   if (!NILP (BVAR (XBUFFER (w->contents), extra_line_spacing)))
 21919     GIVE_UP (23);
 21920 
 21921   /* Give up if display-line-numbers is in relative mode, or when the
 21922      current line's number needs to be displayed in a distinct face.  */
 21923   if (EQ (Vdisplay_line_numbers, Qrelative)
 21924       || EQ (Vdisplay_line_numbers, Qvisual)
 21925       || (!NILP (Vdisplay_line_numbers)
 21926           && NILP (Finternal_lisp_face_equal_p (Qline_number,
 21927                                                 Qline_number_current_line,
 21928                                                 w->frame))))
 21929     GIVE_UP (24);
 21930 
 21931   /* composition-break-at-point is incompatible with the optimizations
 21932      in this function, because we need to recompose characters when
 21933      point moves off their positions.  */
 21934   if (composition_break_at_point)
 21935     GIVE_UP (27);
 21936 
 21937   /* Make sure beg_unchanged and end_unchanged are up to date.  Do it
 21938      only if buffer has really changed.  The reason is that the gap is
 21939      initially at Z for freshly visited files.  The code below would
 21940      set end_unchanged to 0 in that case.  */
 21941   if (MODIFF > SAVE_MODIFF
 21942       /* This seems to happen sometimes after saving a buffer.  */
 21943       || BEG_UNCHANGED + END_UNCHANGED > Z_BYTE)
 21944     {
 21945       if (GPT - BEG < BEG_UNCHANGED)
 21946         BEG_UNCHANGED = GPT - BEG;
 21947       if (Z - GPT < END_UNCHANGED)
 21948         END_UNCHANGED = Z - GPT;
 21949     }
 21950 
 21951   /* The position of the first and last character that has been changed.  */
 21952   first_changed_charpos = BEG + BEG_UNCHANGED;
 21953   last_changed_charpos  = Z - END_UNCHANGED;
 21954 
 21955   /* If window starts after a line end, and the last change is in
 21956      front of that newline, then changes don't affect the display.
 21957      This case happens with stealth-fontification.  Note that although
 21958      the display is unchanged, glyph positions in the matrix have to
 21959      be adjusted, of course.  */
 21960   row = MATRIX_ROW (w->current_matrix, w->window_end_vpos);
 21961   if (MATRIX_ROW_DISPLAYS_TEXT_P (row)
 21962       && ((last_changed_charpos < CHARPOS (start)
 21963            && CHARPOS (start) == BEGV)
 21964           || (last_changed_charpos < CHARPOS (start) - 1
 21965               && FETCH_BYTE (BYTEPOS (start) - 1) == '\n')))
 21966     {
 21967       ptrdiff_t Z_old, Z_delta, Z_BYTE_old, Z_delta_bytes;
 21968       struct glyph_row *r0;
 21969 
 21970       /* Compute how many chars/bytes have been added to or removed
 21971          from the buffer.  */
 21972       Z_old = MATRIX_ROW_END_CHARPOS (row) + w->window_end_pos;
 21973       Z_BYTE_old = MATRIX_ROW_END_BYTEPOS (row) + w->window_end_bytepos;
 21974       Z_delta = Z - Z_old;
 21975       Z_delta_bytes = Z_BYTE - Z_BYTE_old;
 21976 
 21977       /* Give up if PT is not in the window.  Note that it already has
 21978          been checked at the start of try_window_id that PT is not in
 21979          front of the window start.  */
 21980       if (PT >= MATRIX_ROW_END_CHARPOS (row) + Z_delta)
 21981         GIVE_UP (13);
 21982 
 21983       /* If window start is unchanged, we can reuse the whole matrix
 21984          as is, after adjusting glyph positions.  No need to compute
 21985          the window end again, since its offset from Z hasn't changed.  */
 21986       r0 = MATRIX_FIRST_TEXT_ROW (current_matrix);
 21987       if (CHARPOS (start) == MATRIX_ROW_START_CHARPOS (r0) + Z_delta
 21988           && BYTEPOS (start) == MATRIX_ROW_START_BYTEPOS (r0) + Z_delta_bytes
 21989           /* PT must not be in a partially visible line.  */
 21990           && !(PT >= MATRIX_ROW_START_CHARPOS (row) + Z_delta
 21991                && MATRIX_ROW_BOTTOM_Y (row) > window_text_bottom_y (w)))
 21992         {
 21993           /* Adjust positions in the glyph matrix.  */
 21994           if (Z_delta || Z_delta_bytes)
 21995             {
 21996               struct glyph_row *r1
 21997                 = MATRIX_BOTTOM_TEXT_ROW (current_matrix, w);
 21998               increment_matrix_positions (w->current_matrix,
 21999                                           MATRIX_ROW_VPOS (r0, current_matrix),
 22000                                           MATRIX_ROW_VPOS (r1, current_matrix),
 22001                                           Z_delta, Z_delta_bytes);
 22002             }
 22003 
 22004           /* Set the cursor.  */
 22005           row = row_containing_pos (w, PT, r0, NULL, 0);
 22006           if (row)
 22007             set_cursor_from_row (w, row, current_matrix, 0, 0, 0, 0);
 22008           return 1;
 22009         }
 22010     }
 22011 
 22012   /* Handle the case that changes are all below what is displayed in
 22013      the window, and that PT is in the window.  This shortcut cannot
 22014      be taken if ZV is visible in the window, and text has been added
 22015      there that is visible in the window.  */
 22016   if (first_changed_charpos >= MATRIX_ROW_END_CHARPOS (row)
 22017       /* ZV is not visible in the window, or there are no
 22018          changes at ZV, actually.  */
 22019       && (current_matrix->zv > MATRIX_ROW_END_CHARPOS (row)
 22020           || first_changed_charpos == last_changed_charpos))
 22021     {
 22022       struct glyph_row *r0;
 22023 
 22024       /* Give up if PT is not in the window.  Note that it already has
 22025          been checked at the start of try_window_id that PT is not in
 22026          front of the window start.  */
 22027       if (PT >= MATRIX_ROW_END_CHARPOS (row))
 22028         GIVE_UP (14);
 22029 
 22030       /* If window start is unchanged, we can reuse the whole matrix
 22031          as is, without changing glyph positions since no text has
 22032          been added/removed in front of the window end.  */
 22033       r0 = MATRIX_FIRST_TEXT_ROW (current_matrix);
 22034       if (TEXT_POS_EQUAL_P (start, r0->minpos)
 22035           /* PT must not be in a partially visible line.  */
 22036           && !(PT >= MATRIX_ROW_START_CHARPOS (row)
 22037                && MATRIX_ROW_BOTTOM_Y (row) > window_text_bottom_y (w)))
 22038         {
 22039           /* We have to compute the window end anew since text
 22040              could have been added/removed after it.  */
 22041           w->window_end_pos = Z - MATRIX_ROW_END_CHARPOS (row);
 22042           w->window_end_bytepos = Z_BYTE - MATRIX_ROW_END_BYTEPOS (row);
 22043 
 22044           /* Set the cursor.  */
 22045           row = row_containing_pos (w, PT, r0, NULL, 0);
 22046           if (row)
 22047             set_cursor_from_row (w, row, current_matrix, 0, 0, 0, 0);
 22048           return 2;
 22049         }
 22050     }
 22051 
 22052   /* Give up if window start is in the changed area.
 22053 
 22054      The condition used to read
 22055 
 22056      (BEG_UNCHANGED + END_UNCHANGED != Z - BEG && ...)
 22057 
 22058      but why that was tested escapes me at the moment.  */
 22059   if (CHARPOS (start) >= first_changed_charpos
 22060       && CHARPOS (start) <= last_changed_charpos)
 22061     GIVE_UP (15);
 22062 
 22063   /* Check that window start agrees with the start of the first glyph
 22064      row in its current matrix.  Check this after we know the window
 22065      start is not in changed text, otherwise positions would not be
 22066      comparable.  */
 22067   row = MATRIX_FIRST_TEXT_ROW (current_matrix);
 22068   if (!TEXT_POS_EQUAL_P (start, row->minpos))
 22069     GIVE_UP (16);
 22070 
 22071   /* Give up if the window ends in strings.  Overlay strings
 22072      at the end are difficult to handle, so don't try.  */
 22073   row = MATRIX_ROW (current_matrix, w->window_end_vpos);
 22074   if (MATRIX_ROW_START_CHARPOS (row) == MATRIX_ROW_END_CHARPOS (row))
 22075     GIVE_UP (20);
 22076 
 22077   /* Can't let scroll_run_hook below run on w32 GUI frames when
 22078      position of point is indicated by the system caret, because
 22079      scrolling the display will then "copy" the pixels used by the
 22080      caret.  */
 22081 #ifdef HAVE_NTGUI
 22082   if (FRAME_W32_P (f) && w32_use_visible_system_caret)
 22083     GIVE_UP (25);
 22084 #endif
 22085 
 22086   /* Compute the position at which we have to start displaying new
 22087      lines.  Some of the lines at the top of the window might be
 22088      reusable because they are not displaying changed text.  Find the
 22089      last row in W's current matrix not affected by changes at the
 22090      start of current_buffer.  Value is null if changes start in the
 22091      first line of window.  */
 22092   last_unchanged_at_beg_row = find_last_unchanged_at_beg_row (w);
 22093   if (last_unchanged_at_beg_row)
 22094     {
 22095       /* Avoid starting to display in the middle of a character, a TAB
 22096          for instance.  This is easier than to set up the iterator
 22097          exactly, and it's not a frequent case, so the additional
 22098          effort wouldn't really pay off.  */
 22099       while ((MATRIX_ROW_ENDS_IN_MIDDLE_OF_CHAR_P (last_unchanged_at_beg_row)
 22100               || last_unchanged_at_beg_row->ends_in_newline_from_string_p)
 22101              && last_unchanged_at_beg_row > w->current_matrix->rows)
 22102         --last_unchanged_at_beg_row;
 22103 
 22104       if (MATRIX_ROW_ENDS_IN_MIDDLE_OF_CHAR_P (last_unchanged_at_beg_row))
 22105         GIVE_UP (17);
 22106 
 22107       if (! init_to_row_end (&it, w, last_unchanged_at_beg_row))
 22108         GIVE_UP (18);
 22109       /* Give up if the row starts with a display property that draws
 22110          on the fringes, since that could prevent correct display of
 22111          line-prefix and wrap-prefix.  */
 22112       if (it.sp > 1
 22113           && it.method == GET_FROM_IMAGE && it.image_id == -1)
 22114         GIVE_UP (26);
 22115       start_pos = it.current.pos;
 22116 
 22117       /* Start displaying new lines in the desired matrix at the same
 22118          vpos we would use in the current matrix, i.e. below
 22119          last_unchanged_at_beg_row.  */
 22120       it.vpos = 1 + MATRIX_ROW_VPOS (last_unchanged_at_beg_row,
 22121                                      current_matrix);
 22122       it.glyph_row = MATRIX_ROW (desired_matrix, it.vpos);
 22123       it.current_y = MATRIX_ROW_BOTTOM_Y (last_unchanged_at_beg_row);
 22124 
 22125       eassert (it.hpos == 0 && it.current_x == 0);
 22126     }
 22127   else
 22128     {
 22129       /* There are no reusable lines at the start of the window.
 22130          Start displaying in the first text line.  */
 22131       start_display (&it, w, start);
 22132       it.vpos = it.first_vpos;
 22133       start_pos = it.current.pos;
 22134     }
 22135 
 22136   /* Find the first row that is not affected by changes at the end of
 22137      the buffer.  Value will be null if there is no unchanged row, in
 22138      which case we must redisplay to the end of the window.  delta
 22139      will be set to the value by which buffer positions beginning with
 22140      first_unchanged_at_end_row have to be adjusted due to text
 22141      changes.  */
 22142   first_unchanged_at_end_row
 22143     = find_first_unchanged_at_end_row (w, &delta, &delta_bytes);
 22144   IF_DEBUG (debug_delta = delta);
 22145   IF_DEBUG (debug_delta_bytes = delta_bytes);
 22146 
 22147   /* Set stop_pos to the buffer position up to which we will have to
 22148      display new lines.  If first_unchanged_at_end_row != NULL, this
 22149      is the buffer position of the start of the line displayed in that
 22150      row.  For first_unchanged_at_end_row == NULL, use 0 to indicate
 22151      that we don't stop at a buffer position.  */
 22152   stop_pos = 0;
 22153   if (first_unchanged_at_end_row)
 22154     {
 22155       eassert (last_unchanged_at_beg_row == NULL
 22156                || first_unchanged_at_end_row >= last_unchanged_at_beg_row);
 22157 
 22158       /* If this is a continuation line, move forward to the next one
 22159          that isn't.  Changes in lines above affect this line.
 22160          Caution: this may move first_unchanged_at_end_row to a row
 22161          not displaying text.  */
 22162       while (MATRIX_ROW_CONTINUATION_LINE_P (first_unchanged_at_end_row)
 22163              && MATRIX_ROW_DISPLAYS_TEXT_P (first_unchanged_at_end_row)
 22164              && (MATRIX_ROW_BOTTOM_Y (first_unchanged_at_end_row)
 22165                  < it.last_visible_y))
 22166         ++first_unchanged_at_end_row;
 22167 
 22168       if (!MATRIX_ROW_DISPLAYS_TEXT_P (first_unchanged_at_end_row)
 22169           || (MATRIX_ROW_BOTTOM_Y (first_unchanged_at_end_row)
 22170               >= it.last_visible_y))
 22171         first_unchanged_at_end_row = NULL;
 22172       else
 22173         {
 22174           stop_pos = (MATRIX_ROW_START_CHARPOS (first_unchanged_at_end_row)
 22175                       + delta);
 22176           first_unchanged_at_end_vpos
 22177             = MATRIX_ROW_VPOS (first_unchanged_at_end_row, current_matrix);
 22178           eassert (stop_pos >= Z - END_UNCHANGED);
 22179         }
 22180     }
 22181   else if (last_unchanged_at_beg_row == NULL)
 22182     GIVE_UP (19);
 22183 
 22184 
 22185 #ifdef GLYPH_DEBUG
 22186 
 22187   /* Either there is no unchanged row at the end, or the one we have
 22188      now displays text.  This is a necessary condition for the window
 22189      end pos calculation at the end of this function.  */
 22190   eassert (first_unchanged_at_end_row == NULL
 22191            || MATRIX_ROW_DISPLAYS_TEXT_P (first_unchanged_at_end_row));
 22192 
 22193   debug_last_unchanged_at_beg_vpos
 22194     = (last_unchanged_at_beg_row
 22195        ? MATRIX_ROW_VPOS (last_unchanged_at_beg_row, current_matrix)
 22196        : -1);
 22197   debug_first_unchanged_at_end_vpos = first_unchanged_at_end_vpos;
 22198 
 22199 #endif /* GLYPH_DEBUG */
 22200 
 22201 
 22202   /* Display new lines.  Set last_text_row to the last new line
 22203      displayed which has text on it, i.e. might end up as being the
 22204      line where the window_end_vpos is.  */
 22205   w->cursor.vpos = -1;
 22206   last_text_row = NULL;
 22207   overlay_arrow_seen = false;
 22208   if (it.current_y < it.last_visible_y
 22209       && !f->fonts_changed
 22210       && (first_unchanged_at_end_row == NULL
 22211           || IT_CHARPOS (it) < stop_pos))
 22212     it.glyph_row->reversed_p = false;
 22213   while (it.current_y < it.last_visible_y
 22214          && !f->fonts_changed
 22215          && (first_unchanged_at_end_row == NULL
 22216              || IT_CHARPOS (it) < stop_pos))
 22217     {
 22218       if (display_line (&it, -1))
 22219         last_text_row = it.glyph_row - 1;
 22220     }
 22221 
 22222   if (f->fonts_changed)
 22223     return -1;
 22224 
 22225   /* The redisplay iterations in display_line above could have
 22226      triggered font-lock, which could have done something that
 22227      invalidates IT->w window's end-point information, on which we
 22228      rely below.  E.g., one package, which will remain unnamed, used
 22229      to install a font-lock-fontify-region-function that called
 22230      bury-buffer, whose side effect is to switch the buffer displayed
 22231      by IT->w, and that predictably resets IT->w's window_end_valid
 22232      flag, which we already tested at the entry to this function.
 22233      Amply punish such packages/modes by giving up on this
 22234      optimization in those cases.  */
 22235   if (!w->window_end_valid)
 22236     {
 22237       clear_glyph_matrix (w->desired_matrix);
 22238       return -1;
 22239     }
 22240 
 22241   /* Compute differences in buffer positions, y-positions etc.  for
 22242      lines reused at the bottom of the window.  Compute what we can
 22243      scroll.  */
 22244   if (first_unchanged_at_end_row
 22245       /* No lines reused because we displayed everything up to the
 22246          bottom of the window.  */
 22247       && it.current_y < it.last_visible_y)
 22248     {
 22249       dvpos = (it.vpos
 22250                - MATRIX_ROW_VPOS (first_unchanged_at_end_row,
 22251                                   current_matrix));
 22252       dy = it.current_y - first_unchanged_at_end_row->y;
 22253       run.current_y = first_unchanged_at_end_row->y;
 22254       run.desired_y = run.current_y + dy;
 22255       run.height = it.last_visible_y - max (run.current_y, run.desired_y);
 22256     }
 22257   else
 22258     {
 22259       delta = delta_bytes = dvpos = dy
 22260         = run.current_y = run.desired_y = run.height = 0;
 22261       first_unchanged_at_end_row = NULL;
 22262     }
 22263   IF_DEBUG ((debug_dvpos = dvpos, debug_dy = dy));
 22264 
 22265 
 22266   /* Find the cursor if not already found.  We have to decide whether
 22267      PT will appear on this window (it sometimes doesn't, but this is
 22268      not a very frequent case.)  This decision has to be made before
 22269      the current matrix is altered.  A value of cursor.vpos < 0 means
 22270      that PT is either in one of the lines beginning at
 22271      first_unchanged_at_end_row or below the window.  Don't care for
 22272      lines that might be displayed later at the window end; as
 22273      mentioned, this is not a frequent case.  */
 22274   if (w->cursor.vpos < 0)
 22275     {
 22276       /* Cursor in unchanged rows at the top?  */
 22277       if (PT < CHARPOS (start_pos)
 22278           && last_unchanged_at_beg_row)
 22279         {
 22280           row = row_containing_pos (w, PT,
 22281                                     MATRIX_FIRST_TEXT_ROW (w->current_matrix),
 22282                                     last_unchanged_at_beg_row + 1, 0);
 22283           if (row)
 22284             set_cursor_from_row (w, row, w->current_matrix, 0, 0, 0, 0);
 22285         }
 22286 
 22287       /* Start from first_unchanged_at_end_row looking for PT.  */
 22288       else if (first_unchanged_at_end_row)
 22289         {
 22290           row = row_containing_pos (w, PT - delta,
 22291                                     first_unchanged_at_end_row, NULL, 0);
 22292           if (row)
 22293             set_cursor_from_row (w, row, w->current_matrix, delta,
 22294                                  delta_bytes, dy, dvpos);
 22295         }
 22296 
 22297       /* Give up if cursor was not found.  */
 22298       if (w->cursor.vpos < 0)
 22299         {
 22300           clear_glyph_matrix (w->desired_matrix);
 22301           return -1;
 22302         }
 22303     }
 22304 
 22305   /* Don't let the cursor end in the scroll margins.  */
 22306   {
 22307     int top_scroll_margin = window_scroll_margin (w, MARGIN_IN_PIXELS);
 22308     int bot_scroll_margin = top_scroll_margin;
 22309     int cursor_height = MATRIX_ROW (w->desired_matrix, w->cursor.vpos)->height;
 22310 
 22311     if (window_wants_header_line (w))
 22312       top_scroll_margin += CURRENT_HEADER_LINE_HEIGHT (w);
 22313     if (window_wants_tab_line (w))
 22314       top_scroll_margin += CURRENT_TAB_LINE_HEIGHT (w);
 22315 
 22316     if ((w->cursor.y < top_scroll_margin
 22317          && CHARPOS (start) > BEGV)
 22318         /* Old redisplay didn't take scroll margin into account at the bottom,
 22319            but then global-hl-line-mode doesn't scroll.  KFS 2004-06-14 */
 22320         || (w->cursor.y
 22321             + (cursor_row_fully_visible_p (w, false, true, true)
 22322                ? 1
 22323                : cursor_height + bot_scroll_margin)) > it.last_visible_y)
 22324       {
 22325         w->cursor.vpos = -1;
 22326         clear_glyph_matrix (w->desired_matrix);
 22327         return -1;
 22328       }
 22329   }
 22330 
 22331   /* Scroll the display.  Do it before changing the current matrix so
 22332      that xterm.c doesn't get confused about where the cursor glyph is
 22333      found.  */
 22334   if (dy && run.height)
 22335     {
 22336       update_begin (f);
 22337 
 22338       if (FRAME_WINDOW_P (f))
 22339         {
 22340 #ifdef HAVE_WINDOW_SYSTEM
 22341           gui_update_window_begin (w);
 22342           FRAME_RIF (f)->clear_window_mouse_face (w);
 22343           FRAME_RIF (f)->scroll_run_hook (w, &run);
 22344           gui_update_window_end (w, false, false);
 22345 #endif
 22346         }
 22347       else
 22348         {
 22349           /* Terminal frame.  In this case, dvpos gives the number of
 22350              lines to scroll by; dvpos < 0 means scroll up.  */
 22351           int from_vpos
 22352             = MATRIX_ROW_VPOS (first_unchanged_at_end_row, w->current_matrix);
 22353           int from = WINDOW_TOP_EDGE_LINE (w) + from_vpos;
 22354           int end = (WINDOW_TOP_EDGE_LINE (w)
 22355                      + window_wants_tab_line (w)
 22356                      + window_wants_header_line (w)
 22357                      + window_internal_height (w));
 22358 
 22359           gui_clear_window_mouse_face (w);
 22360 
 22361           /* Perform the operation on the screen.  */
 22362           if (dvpos > 0)
 22363             {
 22364               /* Scroll last_unchanged_at_beg_row to the end of the
 22365                  window down dvpos lines.  */
 22366               set_terminal_window (f, end);
 22367 
 22368               /* On dumb terminals delete dvpos lines at the end
 22369                  before inserting dvpos empty lines.  */
 22370               if (!FRAME_SCROLL_REGION_OK (f))
 22371                 ins_del_lines (f, end - dvpos, -dvpos);
 22372 
 22373               /* Insert dvpos empty lines in front of
 22374                  last_unchanged_at_beg_row.  */
 22375               ins_del_lines (f, from, dvpos);
 22376             }
 22377           else if (dvpos < 0)
 22378             {
 22379               /* Scroll up last_unchanged_at_beg_vpos to the end of
 22380                  the window to last_unchanged_at_beg_vpos - |dvpos|.  */
 22381               set_terminal_window (f, end);
 22382 
 22383               /* Delete dvpos lines in front of
 22384                  last_unchanged_at_beg_vpos.  ins_del_lines will set
 22385                  the cursor to the given vpos and emit |dvpos| delete
 22386                  line sequences.  */
 22387               ins_del_lines (f, from + dvpos, dvpos);
 22388 
 22389               /* On a dumb terminal insert dvpos empty lines at the
 22390                  end.  */
 22391               if (!FRAME_SCROLL_REGION_OK (f))
 22392                 ins_del_lines (f, end + dvpos, -dvpos);
 22393             }
 22394 
 22395           set_terminal_window (f, 0);
 22396         }
 22397 
 22398       update_end (f);
 22399     }
 22400 
 22401   /* Shift reused rows of the current matrix to the right position.
 22402      BOTTOM_ROW is the last + 1 row in the current matrix reserved for
 22403      text.  */
 22404   bottom_row = MATRIX_BOTTOM_TEXT_ROW (current_matrix, w);
 22405   bottom_vpos = MATRIX_ROW_VPOS (bottom_row, current_matrix);
 22406   if (dvpos < 0)
 22407     {
 22408       rotate_matrix (current_matrix, first_unchanged_at_end_vpos + dvpos,
 22409                      bottom_vpos, dvpos);
 22410       clear_glyph_matrix_rows (current_matrix, bottom_vpos + dvpos,
 22411                                bottom_vpos);
 22412     }
 22413   else if (dvpos > 0)
 22414     {
 22415       rotate_matrix (current_matrix, first_unchanged_at_end_vpos,
 22416                      bottom_vpos, dvpos);
 22417       clear_glyph_matrix_rows (current_matrix, first_unchanged_at_end_vpos,
 22418                                first_unchanged_at_end_vpos + dvpos);
 22419     }
 22420 
 22421   /* For frame-based redisplay, make sure that current frame and window
 22422      matrix are in sync with respect to glyph memory.  */
 22423   if (!FRAME_WINDOW_P (f))
 22424     sync_frame_with_window_matrix_rows (w);
 22425 
 22426   /* Adjust buffer positions in reused rows.  */
 22427   if (delta || delta_bytes)
 22428     increment_matrix_positions (current_matrix,
 22429                                 first_unchanged_at_end_vpos + dvpos,
 22430                                 bottom_vpos, delta, delta_bytes);
 22431 
 22432   /* Adjust Y positions.  */
 22433   if (dy)
 22434     shift_glyph_matrix (w, current_matrix,
 22435                         first_unchanged_at_end_vpos + dvpos,
 22436                         bottom_vpos, dy);
 22437 
 22438   if (first_unchanged_at_end_row)
 22439     {
 22440       first_unchanged_at_end_row += dvpos;
 22441       if (first_unchanged_at_end_row->y >= it.last_visible_y
 22442           || !MATRIX_ROW_DISPLAYS_TEXT_P (first_unchanged_at_end_row))
 22443         first_unchanged_at_end_row = NULL;
 22444     }
 22445 
 22446   /* If scrolling up, there may be some lines to display at the end of
 22447      the window.  */
 22448   last_text_row_at_end = NULL;
 22449   if (dy < 0)
 22450     {
 22451       /* Scrolling up can leave for example a partially visible line
 22452          at the end of the window to be redisplayed.  */
 22453       /* Set last_row to the glyph row in the current matrix where the
 22454          window end line is found.  It has been moved up or down in
 22455          the matrix by dvpos.  */
 22456       int last_vpos = w->window_end_vpos + dvpos;
 22457       struct glyph_row *last_row = MATRIX_ROW (current_matrix, last_vpos);
 22458 
 22459       /* If last_row is the window end line, it should display text.  */
 22460       eassert (MATRIX_ROW_DISPLAYS_TEXT_P (last_row));
 22461 
 22462       /* If window end line was partially visible before, begin
 22463          displaying at that line.  Otherwise begin displaying with the
 22464          line following it.  */
 22465       if (MATRIX_ROW_BOTTOM_Y (last_row) - dy >= it.last_visible_y)
 22466         {
 22467           init_to_row_start (&it, w, last_row);
 22468           it.vpos = last_vpos;
 22469           it.current_y = last_row->y;
 22470         }
 22471       else
 22472         {
 22473           init_to_row_end (&it, w, last_row);
 22474           it.vpos = 1 + last_vpos;
 22475           it.current_y = MATRIX_ROW_BOTTOM_Y (last_row);
 22476           ++last_row;
 22477         }
 22478 
 22479       /* We may start in a continuation line.  If so, we have to
 22480          get the right continuation_lines_width and current_x.  */
 22481       it.continuation_lines_width = last_row->continuation_lines_width;
 22482       it.hpos = it.current_x = 0;
 22483 
 22484       /* Display the rest of the lines at the window end.  */
 22485       it.glyph_row = MATRIX_ROW (desired_matrix, it.vpos);
 22486       while (it.current_y < it.last_visible_y && !f->fonts_changed)
 22487         {
 22488           /* Is it always sure that the display agrees with lines in
 22489              the current matrix?  I don't think so, so we mark rows
 22490              displayed invalid in the current matrix by setting their
 22491              enabled_p flag to false.  */
 22492           SET_MATRIX_ROW_ENABLED_P (w->current_matrix, it.vpos, false);
 22493           if (display_line (&it, w->cursor.vpos))
 22494             last_text_row_at_end = it.glyph_row - 1;
 22495         }
 22496     }
 22497 
 22498   /* Update window_end_pos and window_end_vpos.  */
 22499   if (first_unchanged_at_end_row && !last_text_row_at_end)
 22500     {
 22501       /* Window end line if one of the preserved rows from the current
 22502          matrix.  Set row to the last row displaying text in current
 22503          matrix starting at first_unchanged_at_end_row, after
 22504          scrolling.  */
 22505       eassert (MATRIX_ROW_DISPLAYS_TEXT_P (first_unchanged_at_end_row));
 22506       row = find_last_row_displaying_text (w->current_matrix, &it,
 22507                                            first_unchanged_at_end_row);
 22508       eassume (row && MATRIX_ROW_DISPLAYS_TEXT_P (row));
 22509       adjust_window_ends (w, row, true);
 22510       eassert (w->window_end_bytepos >= 0);
 22511       IF_DEBUG (debug_method_add (w, "A"));
 22512     }
 22513   else if (last_text_row_at_end)
 22514     {
 22515       adjust_window_ends (w, last_text_row_at_end, false);
 22516       eassert (w->window_end_bytepos >= 0);
 22517       IF_DEBUG (debug_method_add (w, "B"));
 22518     }
 22519   else if (last_text_row)
 22520     {
 22521       /* We have displayed either to the end of the window or at the
 22522          end of the window, i.e. the last row with text is to be found
 22523          in the desired matrix.  */
 22524       adjust_window_ends (w, last_text_row, false);
 22525       eassert (w->window_end_bytepos >= 0);
 22526     }
 22527   else if (first_unchanged_at_end_row == NULL
 22528            && last_text_row == NULL
 22529            && last_text_row_at_end == NULL)
 22530     {
 22531       /* Displayed to end of window, but no line containing text was
 22532          displayed.  Lines were deleted at the end of the window.  */
 22533       int first_vpos = window_wants_tab_line (w) + window_wants_header_line (w);
 22534       int vpos = w->window_end_vpos;
 22535       struct glyph_row *current_row = current_matrix->rows + vpos;
 22536       struct glyph_row *desired_row = desired_matrix->rows + vpos;
 22537 
 22538       for (row = NULL; !row; --vpos, --current_row, --desired_row)
 22539         {
 22540           eassert (first_vpos <= vpos);
 22541           if (desired_row->enabled_p)
 22542             {
 22543               if (MATRIX_ROW_DISPLAYS_TEXT_P (desired_row))
 22544                 row = desired_row;
 22545             }
 22546           else if (MATRIX_ROW_DISPLAYS_TEXT_P (current_row))
 22547             row  = current_row;
 22548         }
 22549 
 22550       w->window_end_vpos = vpos + 1;
 22551       w->window_end_pos = Z - MATRIX_ROW_END_CHARPOS (row);
 22552       w->window_end_bytepos = Z_BYTE - MATRIX_ROW_END_BYTEPOS (row);
 22553       eassert (w->window_end_bytepos >= 0);
 22554       IF_DEBUG (debug_method_add (w, "C"));
 22555     }
 22556   else
 22557     emacs_abort ();
 22558 
 22559   IF_DEBUG ((debug_end_pos = w->window_end_pos,
 22560              debug_end_vpos = w->window_end_vpos));
 22561 
 22562   /* Record that display has not been completed.  */
 22563   w->window_end_valid = false;
 22564   w->desired_matrix->no_scrolling_p = true;
 22565   return 3;
 22566 
 22567 #undef GIVE_UP
 22568 }
 22569 
 22570 
 22571 
 22572 /***********************************************************************
 22573                         More debugging support
 22574  ***********************************************************************/
 22575 
 22576 #ifdef GLYPH_DEBUG
 22577 
 22578 void dump_glyph_row (struct glyph_row *, int, int) EXTERNALLY_VISIBLE;
 22579 void dump_glyph_matrix (struct glyph_matrix *, int) EXTERNALLY_VISIBLE;
 22580 void dump_glyph (struct glyph_row *, struct glyph *, int) EXTERNALLY_VISIBLE;
 22581 
 22582 
 22583 /* Dump the contents of glyph matrix MATRIX on stderr.
 22584 
 22585    GLYPHS 0 means don't show glyph contents.
 22586    GLYPHS 1 means show glyphs in short form
 22587    GLYPHS > 1 means show glyphs in long form.  */
 22588 
 22589 void
 22590 dump_glyph_matrix (struct glyph_matrix *matrix, int glyphs)
 22591 {
 22592   int i;
 22593   for (i = 0; i < matrix->nrows; ++i)
 22594     dump_glyph_row (MATRIX_ROW (matrix, i), i, glyphs);
 22595 }
 22596 
 22597 
 22598 /* Dump contents of glyph GLYPH to stderr.  ROW and AREA are
 22599    the glyph row and area where the glyph comes from.  */
 22600 
 22601 void
 22602 dump_glyph (struct glyph_row *row, struct glyph *glyph, int area)
 22603 {
 22604   if (glyph->type == CHAR_GLYPH
 22605       || glyph->type == GLYPHLESS_GLYPH)
 22606     {
 22607       fprintf (stderr,
 22608                "  %5"pD"d     %c %9"pD"d   %c %3d 0x%06x      %c %4d %1.1d%1.1d\n",
 22609                glyph - row->glyphs[TEXT_AREA],
 22610                (glyph->type == CHAR_GLYPH
 22611                 ? 'C'
 22612                 : 'G'),
 22613                glyph->charpos,
 22614                (BUFFERP (glyph->object)
 22615                 ? 'B'
 22616                 : (STRINGP (glyph->object)
 22617                    ? 'S'
 22618                    : (NILP (glyph->object)
 22619                       ? '0'
 22620                       : '-'))),
 22621                glyph->pixel_width,
 22622                glyph->u.ch,
 22623                (glyph->u.ch < 0x80 && glyph->u.ch >= ' '
 22624                 ? (int) glyph->u.ch
 22625                 : '.'),
 22626                glyph->face_id,
 22627                glyph->left_box_line_p,
 22628                glyph->right_box_line_p);
 22629     }
 22630   else if (glyph->type == STRETCH_GLYPH)
 22631     {
 22632       fprintf (stderr,
 22633                "  %5"pD"d     %c %9"pD"d   %c %3d 0x%06x      %c %4d %1.1d%1.1d\n",
 22634                glyph - row->glyphs[TEXT_AREA],
 22635                'S',
 22636                glyph->charpos,
 22637                (BUFFERP (glyph->object)
 22638                 ? 'B'
 22639                 : (STRINGP (glyph->object)
 22640                    ? 'S'
 22641                    : (NILP (glyph->object)
 22642                       ? '0'
 22643                       : '-'))),
 22644                glyph->pixel_width,
 22645                0u,
 22646                ' ',
 22647                glyph->face_id,
 22648                glyph->left_box_line_p,
 22649                glyph->right_box_line_p);
 22650     }
 22651   else if (glyph->type == IMAGE_GLYPH)
 22652     {
 22653       fprintf (stderr,
 22654                "  %5"pD"d     %c %9"pD"d   %c %3d 0x%06x      %c %4d %1.1d%1.1d\n",
 22655                glyph - row->glyphs[TEXT_AREA],
 22656                'I',
 22657                glyph->charpos,
 22658                (BUFFERP (glyph->object)
 22659                 ? 'B'
 22660                 : (STRINGP (glyph->object)
 22661                    ? 'S'
 22662                    : (NILP (glyph->object)
 22663                       ? '0'
 22664                       : '-'))),
 22665                glyph->pixel_width,
 22666                (unsigned int) glyph->u.img_id,
 22667                '.',
 22668                glyph->face_id,
 22669                glyph->left_box_line_p,
 22670                glyph->right_box_line_p);
 22671     }
 22672   else if (glyph->type == COMPOSITE_GLYPH)
 22673     {
 22674       fprintf (stderr,
 22675                "  %5"pD"d     %c %9"pD"d   %c %3d 0x%06x",
 22676                glyph - row->glyphs[TEXT_AREA],
 22677                '+',
 22678                glyph->charpos,
 22679                (BUFFERP (glyph->object)
 22680                 ? 'B'
 22681                 : (STRINGP (glyph->object)
 22682                    ? 'S'
 22683                    : (NILP (glyph->object)
 22684                       ? '0'
 22685                       : '-'))),
 22686                glyph->pixel_width,
 22687                (unsigned int) glyph->u.cmp.id);
 22688       if (glyph->u.cmp.automatic)
 22689         fprintf (stderr,
 22690                  "[%d-%d]",
 22691                  glyph->slice.cmp.from, glyph->slice.cmp.to);
 22692       fprintf (stderr, " . %4d %1.1d%1.1d\n",
 22693                glyph->face_id,
 22694                glyph->left_box_line_p,
 22695                glyph->right_box_line_p);
 22696     }
 22697   else if (glyph->type == XWIDGET_GLYPH)
 22698     {
 22699 #ifndef HAVE_XWIDGETS
 22700       eassume (false);
 22701 #else
 22702       fprintf (stderr,
 22703                "  %5td %4c %6td %c %3d %7p %c %4d %1.1d%1.1d\n",
 22704                glyph - row->glyphs[TEXT_AREA],
 22705                'X',
 22706                glyph->charpos,
 22707                (BUFFERP (glyph->object)
 22708                 ? 'B'
 22709                 : (STRINGP (glyph->object)
 22710                    ? 'S'
 22711                    : '-')),
 22712                glyph->pixel_width,
 22713                glyph->u.xwidget,
 22714                '.',
 22715                glyph->face_id,
 22716                glyph->left_box_line_p,
 22717                glyph->right_box_line_p);
 22718 #endif
 22719     }
 22720 }
 22721 
 22722 
 22723 /* Dump the contents of glyph row at VPOS in MATRIX to stderr.
 22724    GLYPHS 0 means don't show glyph contents.
 22725    GLYPHS 1 means show glyphs in short form
 22726    GLYPHS > 1 means show glyphs in long form.  */
 22727 
 22728 void
 22729 dump_glyph_row (struct glyph_row *row, int vpos, int glyphs)
 22730 {
 22731   if (glyphs != 1)
 22732     {
 22733       fputs (("Row     Start       End Used oE><\\CTZFesm     X    Y    W    H    V    A    P\n"
 22734               "==============================================================================\n"),
 22735              stderr);
 22736       fprintf (stderr, "%3d %9"pD"d %9"pD"d %4d %1.1d%1.1d%1.1d%1.1d\
 22737 %1.1d%1.1d%1.1d%1.1d%1.1d%1.1d%1.1d%1.1d  %4d %4d %4d %4d %4d %4d %4d\n",
 22738                vpos,
 22739                MATRIX_ROW_START_CHARPOS (row),
 22740                MATRIX_ROW_END_CHARPOS (row),
 22741                row->used[TEXT_AREA],
 22742                row->contains_overlapping_glyphs_p,
 22743                row->enabled_p,
 22744                row->truncated_on_left_p,
 22745                row->truncated_on_right_p,
 22746                row->continued_p,
 22747                MATRIX_ROW_CONTINUATION_LINE_P (row),
 22748                MATRIX_ROW_DISPLAYS_TEXT_P (row),
 22749                row->ends_at_zv_p,
 22750                row->fill_line_p,
 22751                row->ends_in_middle_of_char_p,
 22752                row->starts_in_middle_of_char_p,
 22753                row->mouse_face_p,
 22754                row->x,
 22755                row->y,
 22756                row->pixel_width,
 22757                row->height,
 22758                row->visible_height,
 22759                row->ascent,
 22760                row->phys_ascent);
 22761       /* The next 3 lines should align to "Start" in the header.  */
 22762       fprintf (stderr, "    %9"pD"d %9"pD"d\t%5d\n", row->start.overlay_string_index,
 22763                row->end.overlay_string_index,
 22764                row->continuation_lines_width);
 22765       fprintf (stderr, "    %9"pD"d %9"pD"d\n",
 22766                CHARPOS (row->start.string_pos),
 22767                CHARPOS (row->end.string_pos));
 22768       fprintf (stderr, "    %9d %9d\n", row->start.dpvec_index,
 22769                row->end.dpvec_index);
 22770     }
 22771 
 22772   if (glyphs > 1)
 22773     {
 22774       int area;
 22775 
 22776       for (area = LEFT_MARGIN_AREA; area < LAST_AREA; ++area)
 22777         {
 22778           struct glyph *glyph = row->glyphs[area];
 22779           struct glyph *glyph_end = glyph + row->used[area];
 22780 
 22781           /* Glyph for a line end in text.  */
 22782           if (area == TEXT_AREA && glyph == glyph_end && glyph->charpos > 0)
 22783             ++glyph_end;
 22784 
 22785           if (glyph < glyph_end)
 22786             fputs (" Glyph#  Type       Pos   O   W     Code      C Face LR\n",
 22787                    stderr);
 22788 
 22789           for (; glyph < glyph_end; ++glyph)
 22790             dump_glyph (row, glyph, area);
 22791         }
 22792     }
 22793   else if (glyphs == 1)
 22794     {
 22795       int area;
 22796       char s[SHRT_MAX + 4];
 22797 
 22798       for (area = LEFT_MARGIN_AREA; area < LAST_AREA; ++area)
 22799         {
 22800           int i;
 22801 
 22802           for (i = 0; i < row->used[area]; ++i)
 22803             {
 22804               struct glyph *glyph = row->glyphs[area] + i;
 22805               if (i == row->used[area] - 1
 22806                   && area == TEXT_AREA
 22807                   && NILP (glyph->object)
 22808                   && glyph->type == CHAR_GLYPH
 22809                   && glyph->u.ch == ' ')
 22810                 {
 22811                   strcpy (&s[i], "[\\n]");
 22812                   i += 4;
 22813                 }
 22814               else if (glyph->type == CHAR_GLYPH
 22815                        && glyph->u.ch < 0x80
 22816                        && glyph->u.ch >= ' ')
 22817                 s[i] = glyph->u.ch;
 22818               else
 22819                 s[i] = '.';
 22820             }
 22821 
 22822           s[i] = '\0';
 22823           fprintf (stderr, "%3d: (%d) '%s'\n", vpos, row->enabled_p, s);
 22824         }
 22825     }
 22826 }
 22827 
 22828 
 22829 DEFUN ("dump-glyph-matrix", Fdump_glyph_matrix,
 22830        Sdump_glyph_matrix, 0, 1, "p",
 22831        doc: /* Dump the current matrix of the selected window to stderr.
 22832 Shows contents of glyph row structures.  With non-nil
 22833 parameter GLYPHS, dump glyphs as well.  If GLYPHS is 1 show
 22834 glyphs in short form, otherwise show glyphs in long form.
 22835 
 22836 Interactively, no argument means show glyphs in short form;
 22837 with numeric argument, its value is passed as the GLYPHS flag.  */)
 22838   (Lisp_Object glyphs)
 22839 {
 22840   struct window *w = XWINDOW (selected_window);
 22841   struct buffer *buffer = XBUFFER (w->contents);
 22842 
 22843   fprintf (stderr, "PT = %"pD"d, BEGV = %"pD"d. ZV = %"pD"d\n",
 22844            BUF_PT (buffer), BUF_BEGV (buffer), BUF_ZV (buffer));
 22845   fprintf (stderr, "Cursor x = %d, y = %d, hpos = %d, vpos = %d\n",
 22846            w->cursor.x, w->cursor.y, w->cursor.hpos, w->cursor.vpos);
 22847   fputs ("=============================================\n", stderr);
 22848   dump_glyph_matrix (w->current_matrix,
 22849                      TYPE_RANGED_FIXNUMP (int, glyphs) ? XFIXNUM (glyphs) : 0);
 22850   return Qnil;
 22851 }
 22852 
 22853 
 22854 DEFUN ("dump-frame-glyph-matrix", Fdump_frame_glyph_matrix,
 22855        Sdump_frame_glyph_matrix, 0, 0, "", doc: /* Dump the current glyph matrix of the selected frame to stderr.
 22856 Only text-mode frames have frame glyph matrices.  */)
 22857   (void)
 22858 {
 22859   struct frame *f = XFRAME (selected_frame);
 22860 
 22861   if (f->current_matrix)
 22862     dump_glyph_matrix (f->current_matrix, 1);
 22863   else
 22864     fputs ("*** This frame doesn't have a frame glyph matrix ***\n", stderr);
 22865   return Qnil;
 22866 }
 22867 
 22868 
 22869 DEFUN ("dump-glyph-row", Fdump_glyph_row, Sdump_glyph_row, 1, 2, "P",
 22870        doc: /* Dump glyph row ROW to stderr.
 22871 Interactively, ROW is the prefix numeric argument and defaults to
 22872 the row which displays point.
 22873 Optional argument GLYPHS 0 means don't dump glyphs.
 22874 GLYPHS 1 means dump glyphs in short form.
 22875 GLYPHS > 1 or omitted means dump glyphs in long form.  */)
 22876   (Lisp_Object row, Lisp_Object glyphs)
 22877 {
 22878   struct glyph_matrix *matrix;
 22879   EMACS_INT vpos;
 22880 
 22881   if (NILP (row))
 22882     {
 22883       int d1, d2, d3, d4, d5, ypos;
 22884       bool visible_p = pos_visible_p (XWINDOW (selected_window), PT,
 22885                                       &d1, &d2, &d3, &d4, &d5, &ypos);
 22886       if (visible_p)
 22887         vpos = ypos;
 22888       else
 22889         vpos = 0;
 22890     }
 22891   else
 22892     {
 22893       CHECK_FIXNUM (row);
 22894       vpos = XFIXNUM (row);
 22895     }
 22896   matrix = XWINDOW (selected_window)->current_matrix;
 22897   if (vpos >= 0 && vpos < matrix->nrows)
 22898     dump_glyph_row (MATRIX_ROW (matrix, vpos),
 22899                     vpos,
 22900                     TYPE_RANGED_FIXNUMP (int, glyphs) ? XFIXNUM (glyphs) : 2);
 22901   return Qnil;
 22902 }
 22903 
 22904 
 22905 DEFUN ("dump-tab-bar-row", Fdump_tab_bar_row, Sdump_tab_bar_row, 1, 2, "P",
 22906        doc: /* Dump glyph row ROW of the tab-bar of the current frame to stderr.
 22907 Interactively, ROW is the prefix numeric argument and defaults to zero.
 22908 GLYPHS 0 means don't dump glyphs.
 22909 GLYPHS 1 means dump glyphs in short form.
 22910 GLYPHS > 1 or omitted means dump glyphs in long form.
 22911 
 22912 If there's no tab-bar, or if the tab-bar is not drawn by Emacs,
 22913 do nothing.  */)
 22914   (Lisp_Object row, Lisp_Object glyphs)
 22915 {
 22916 #if defined (HAVE_WINDOW_SYSTEM)
 22917   struct frame *sf = SELECTED_FRAME ();
 22918   struct glyph_matrix *m = WINDOWP (sf->tab_bar_window)
 22919     ? XWINDOW (sf->tab_bar_window)->current_matrix
 22920     : sf->current_matrix;
 22921   EMACS_INT vpos;
 22922 
 22923   if (NILP (row))
 22924     vpos = WINDOWP (sf->tab_bar_window) ? 0 :
 22925       FRAME_MENU_BAR_LINES (sf) > 0 ? 1 : 0;
 22926   else
 22927     {
 22928       CHECK_FIXNUM (row);
 22929       vpos = XFIXNUM (row);
 22930     }
 22931   if (vpos >= 0 && vpos < m->nrows)
 22932     dump_glyph_row (MATRIX_ROW (m, vpos), vpos,
 22933                     TYPE_RANGED_FIXNUMP (int, glyphs) ? XFIXNUM (glyphs) : 2);
 22934 #endif
 22935   return Qnil;
 22936 }
 22937 
 22938 DEFUN ("dump-tool-bar-row", Fdump_tool_bar_row, Sdump_tool_bar_row, 1, 2, "P",
 22939        doc: /* Dump glyph row ROW of the tool-bar of the current frame to stderr.
 22940 Interactively, ROW is the prefix numeric argument and defaults to zero.
 22941 GLYPHS 0 means don't dump glyphs.
 22942 GLYPHS 1 means dump glyphs in short form.
 22943 GLYPHS > 1 or omitted means dump glyphs in long form.
 22944 
 22945 If there's no tool-bar, or if the tool-bar is not drawn by Emacs,
 22946 do nothing.  */)
 22947   (Lisp_Object row, Lisp_Object glyphs)
 22948 {
 22949 #if defined (HAVE_WINDOW_SYSTEM) && ! defined (HAVE_EXT_TOOL_BAR)
 22950   struct frame *sf = SELECTED_FRAME ();
 22951   struct glyph_matrix *m = XWINDOW (sf->tool_bar_window)->current_matrix;
 22952   EMACS_INT vpos;
 22953 
 22954   if (NILP (row))
 22955     vpos = 0;
 22956   else
 22957     {
 22958       CHECK_FIXNUM (row);
 22959       vpos = XFIXNUM (row);
 22960     }
 22961   if (vpos >= 0 && vpos < m->nrows)
 22962     dump_glyph_row (MATRIX_ROW (m, vpos), vpos,
 22963                     TYPE_RANGED_FIXNUMP (int, glyphs) ? XFIXNUM (glyphs) : 2);
 22964 #endif
 22965   return Qnil;
 22966 }
 22967 
 22968 
 22969 DEFUN ("trace-redisplay", Ftrace_redisplay, Strace_redisplay, 0, 1, "P",
 22970        doc: /* Toggle tracing of redisplay.
 22971 With ARG, turn tracing on if and only if ARG is positive.  */)
 22972   (Lisp_Object arg)
 22973 {
 22974   if (NILP (arg))
 22975     trace_redisplay_p = !trace_redisplay_p;
 22976   else
 22977     {
 22978       arg = Fprefix_numeric_value (arg);
 22979       trace_redisplay_p = XFIXNUM (arg) > 0;
 22980     }
 22981 
 22982   return Qnil;
 22983 }
 22984 
 22985 
 22986 DEFUN ("trace-to-stderr", Ftrace_to_stderr, Strace_to_stderr, 1, MANY, "",
 22987        doc: /* Like `format', but print result to stderr.
 22988 usage: (trace-to-stderr STRING &rest OBJECTS)  */)
 22989   (ptrdiff_t nargs, Lisp_Object *args)
 22990 {
 22991   Lisp_Object s = Fformat (nargs, args);
 22992   fwrite (SDATA (s), 1, SBYTES (s), stderr);
 22993   return Qnil;
 22994 }
 22995 
 22996 #endif /* GLYPH_DEBUG */
 22997 
 22998 
 22999 
 23000 /***********************************************************************
 23001                      Building Desired Matrix Rows
 23002  ***********************************************************************/
 23003 
 23004 /* Return a temporary glyph row holding the glyphs of an overlay arrow.
 23005    Used for non-window-redisplay windows, and for windows without left
 23006    fringe.  */
 23007 
 23008 static struct glyph_row *
 23009 get_overlay_arrow_glyph_row (struct window *w, Lisp_Object overlay_arrow_string)
 23010 {
 23011   struct frame *f = XFRAME (WINDOW_FRAME (w));
 23012   struct buffer *buffer = XBUFFER (w->contents);
 23013   struct buffer *old = current_buffer;
 23014   const unsigned char *arrow_string = SDATA (overlay_arrow_string);
 23015   ptrdiff_t arrow_len = SBYTES (overlay_arrow_string), char_num = 0;
 23016   const unsigned char *arrow_end = arrow_string + arrow_len;
 23017   const unsigned char *p;
 23018   struct it it;
 23019   bool multibyte_p;
 23020   int n_glyphs_before;
 23021 
 23022   set_buffer_temp (buffer);
 23023   init_iterator (&it, w, -1, -1, &scratch_glyph_row, DEFAULT_FACE_ID);
 23024   scratch_glyph_row.reversed_p = false;
 23025   it.glyph_row->used[TEXT_AREA] = 0;
 23026   SET_TEXT_POS (it.position, 0, 0);
 23027 
 23028   multibyte_p = !NILP (BVAR (buffer, enable_multibyte_characters));
 23029   p = arrow_string;
 23030   while (p < arrow_end)
 23031     {
 23032       Lisp_Object face, ilisp;
 23033 
 23034       /* Get the next character.  */
 23035       if (multibyte_p)
 23036         it.c = it.char_to_display = check_char_and_length (p, &it.len);
 23037       else
 23038         {
 23039           it.c = it.char_to_display = *p, it.len = 1;
 23040           if (! ASCII_CHAR_P (it.c))
 23041             it.char_to_display = BYTE8_TO_CHAR (it.c);
 23042         }
 23043       p += it.len;
 23044 
 23045       /* Get its face.  */
 23046       ilisp = make_fixnum (char_num++);
 23047       face = Fget_text_property (ilisp, Qface, overlay_arrow_string);
 23048       it.face_id = compute_char_face (f, it.char_to_display, face);
 23049 
 23050       /* Compute its width, get its glyphs.  */
 23051       n_glyphs_before = it.glyph_row->used[TEXT_AREA];
 23052       SET_TEXT_POS (it.position, -1, -1);
 23053       PRODUCE_GLYPHS (&it);
 23054 
 23055       /* If this character doesn't fit any more in the line, we have
 23056          to remove some glyphs.  */
 23057       if (it.current_x > it.last_visible_x)
 23058         {
 23059           it.glyph_row->used[TEXT_AREA] = n_glyphs_before;
 23060           break;
 23061         }
 23062     }
 23063 
 23064   set_buffer_temp (old);
 23065   return it.glyph_row;
 23066 }
 23067 
 23068 
 23069 /* Insert truncation glyphs at the start of IT->glyph_row.  Which
 23070    glyphs to insert is determined by produce_special_glyphs.  */
 23071 
 23072 static void
 23073 insert_left_trunc_glyphs (struct it *it)
 23074 {
 23075   struct it truncate_it;
 23076   struct glyph *from, *end, *to, *toend;
 23077 
 23078   eassert (!FRAME_WINDOW_P (it->f)
 23079            || (!it->glyph_row->reversed_p
 23080                && WINDOW_LEFT_FRINGE_WIDTH (it->w) == 0)
 23081            || (it->glyph_row->reversed_p
 23082                && WINDOW_RIGHT_FRINGE_WIDTH (it->w) == 0));
 23083 
 23084   /* Get the truncation glyphs.  */
 23085   truncate_it = *it;
 23086   truncate_it.current_x = 0;
 23087   truncate_it.face_id = DEFAULT_FACE_ID;
 23088   truncate_it.glyph_row = &scratch_glyph_row;
 23089   truncate_it.area = TEXT_AREA;
 23090   truncate_it.glyph_row->used[TEXT_AREA] = 0;
 23091   CHARPOS (truncate_it.position) = BYTEPOS (truncate_it.position) = -1;
 23092   truncate_it.object = Qnil;
 23093   produce_special_glyphs (&truncate_it, IT_TRUNCATION);
 23094 
 23095   /* Overwrite glyphs from IT with truncation glyphs.  */
 23096   if (!it->glyph_row->reversed_p)
 23097     {
 23098       short tused = truncate_it.glyph_row->used[TEXT_AREA];
 23099 
 23100       from = truncate_it.glyph_row->glyphs[TEXT_AREA];
 23101       end = from + tused;
 23102       to = it->glyph_row->glyphs[TEXT_AREA];
 23103       toend = to + it->glyph_row->used[TEXT_AREA];
 23104       if (FRAME_WINDOW_P (it->f))
 23105         {
 23106           /* On GUI frames, when variable-size fonts are displayed,
 23107              the truncation glyphs may need more pixels than the row's
 23108              glyphs they overwrite.  We overwrite more glyphs to free
 23109              enough screen real estate, and enlarge the stretch glyph
 23110              on the right (see display_line), if there is one, to
 23111              preserve the screen position of the truncation glyphs on
 23112              the right.  */
 23113           int w = 0;
 23114           struct glyph *g = to;
 23115           short used;
 23116 
 23117           /* The first glyph could be partially visible, in which case
 23118              it->glyph_row->x will be negative.  But we want the left
 23119              truncation glyphs to be aligned at the left margin of the
 23120              window, so we override the x coordinate at which the row
 23121              will begin.  */
 23122           it->glyph_row->x = 0;
 23123           while (g < toend && w < it->truncation_pixel_width)
 23124             {
 23125               w += g->pixel_width;
 23126               ++g;
 23127             }
 23128           if (g - to - tused > 0)
 23129             {
 23130               memmove (to + tused, g, (toend - g) * sizeof(*g));
 23131               it->glyph_row->used[TEXT_AREA] -= g - to - tused;
 23132             }
 23133           used = it->glyph_row->used[TEXT_AREA];
 23134           if (it->glyph_row->truncated_on_right_p
 23135               && WINDOW_RIGHT_FRINGE_WIDTH (it->w) == 0
 23136               && it->glyph_row->glyphs[TEXT_AREA][used - 2].type
 23137               == STRETCH_GLYPH)
 23138             {
 23139               int extra = w - it->truncation_pixel_width;
 23140 
 23141               it->glyph_row->glyphs[TEXT_AREA][used - 2].pixel_width += extra;
 23142             }
 23143         }
 23144 
 23145       while (from < end)
 23146         *to++ = *from++;
 23147 
 23148       /* There may be padding glyphs left over.  Overwrite them too.  */
 23149       if (!FRAME_WINDOW_P (it->f))
 23150         {
 23151           while (to < toend && CHAR_GLYPH_PADDING_P (*to))
 23152             {
 23153               from = truncate_it.glyph_row->glyphs[TEXT_AREA];
 23154               while (from < end)
 23155                 *to++ = *from++;
 23156             }
 23157         }
 23158 
 23159       if (to > toend)
 23160         it->glyph_row->used[TEXT_AREA] = to - it->glyph_row->glyphs[TEXT_AREA];
 23161     }
 23162   else
 23163     {
 23164       short tused = truncate_it.glyph_row->used[TEXT_AREA];
 23165 
 23166       /* In R2L rows, overwrite the last (rightmost) glyphs, and do
 23167          that back to front.  */
 23168       end = truncate_it.glyph_row->glyphs[TEXT_AREA];
 23169       from = end + truncate_it.glyph_row->used[TEXT_AREA] - 1;
 23170       toend = it->glyph_row->glyphs[TEXT_AREA];
 23171       to = toend + it->glyph_row->used[TEXT_AREA] - 1;
 23172       if (FRAME_WINDOW_P (it->f))
 23173         {
 23174           int w = 0;
 23175           struct glyph *g = to;
 23176 
 23177           while (g >= toend && w < it->truncation_pixel_width)
 23178             {
 23179               w += g->pixel_width;
 23180               --g;
 23181             }
 23182           if (to - g - tused > 0)
 23183             to = g + tused;
 23184           if (it->glyph_row->truncated_on_right_p
 23185               && WINDOW_LEFT_FRINGE_WIDTH (it->w) == 0
 23186               && it->glyph_row->glyphs[TEXT_AREA][1].type == STRETCH_GLYPH)
 23187             {
 23188               int extra = w - it->truncation_pixel_width;
 23189 
 23190               it->glyph_row->glyphs[TEXT_AREA][1].pixel_width += extra;
 23191             }
 23192         }
 23193 
 23194       while (from >= end && to >= toend)
 23195         *to-- = *from--;
 23196       if (!FRAME_WINDOW_P (it->f))
 23197         {
 23198           while (to >= toend && CHAR_GLYPH_PADDING_P (*to))
 23199             {
 23200               from =
 23201                 truncate_it.glyph_row->glyphs[TEXT_AREA]
 23202                 + truncate_it.glyph_row->used[TEXT_AREA] - 1;
 23203               while (from >= end && to >= toend)
 23204                 *to-- = *from--;
 23205             }
 23206         }
 23207       if (from >= end)
 23208         {
 23209           /* Need to free some room before prepending additional
 23210              glyphs.  */
 23211           int move_by = from - end + 1;
 23212           struct glyph *g0 = it->glyph_row->glyphs[TEXT_AREA];
 23213           struct glyph *g = g0 + it->glyph_row->used[TEXT_AREA] - 1;
 23214 
 23215           for ( ; g >= g0; g--)
 23216             g[move_by] = *g;
 23217           while (from >= end)
 23218             *to-- = *from--;
 23219           it->glyph_row->used[TEXT_AREA] += move_by;
 23220         }
 23221     }
 23222 }
 23223 
 23224 /* Compute the hash code for ROW.  */
 23225 unsigned
 23226 row_hash (struct glyph_row *row)
 23227 {
 23228   int area, k;
 23229   unsigned hashval = 0;
 23230 
 23231   for (area = LEFT_MARGIN_AREA; area < LAST_AREA; ++area)
 23232     for (k = 0; k < row->used[area]; ++k)
 23233       hashval = ((((hashval << 4) + (hashval >> 24)) & 0x0fffffff)
 23234                   + row->glyphs[area][k].u.val
 23235                   + row->glyphs[area][k].face_id
 23236                   + row->glyphs[area][k].padding_p
 23237                   + (row->glyphs[area][k].type << 2));
 23238 
 23239   return hashval;
 23240 }
 23241 
 23242 /* Compute the pixel height and width of IT->glyph_row.
 23243 
 23244    Most of the time, ascent and height of a display line will be equal
 23245    to the max_ascent and max_height values of the display iterator
 23246    structure.  This is not the case if
 23247 
 23248    1. We hit ZV without displaying anything.  In this case, max_ascent
 23249    and max_height will be zero.
 23250 
 23251    2. We have some glyphs that don't contribute to the line height.
 23252    (The glyph row flag contributes_to_line_height_p is for future
 23253    pixmap extensions).
 23254 
 23255    The first case is easily covered by using default values because in
 23256    these cases, the line height does not really matter, except that it
 23257    must not be zero.  */
 23258 
 23259 static void
 23260 compute_line_metrics (struct it *it)
 23261 {
 23262   struct glyph_row *row = it->glyph_row;
 23263 
 23264   if (FRAME_WINDOW_P (it->f))
 23265     {
 23266       int i, min_y, max_y;
 23267 
 23268       /* The line may consist of one space only, that was added to
 23269          place the cursor on it.  If so, the row's height hasn't been
 23270          computed yet.  */
 23271       if (row->height == 0)
 23272         {
 23273           if (it->max_ascent + it->max_descent == 0)
 23274             it->max_descent = it->max_phys_descent = FRAME_LINE_HEIGHT (it->f);
 23275           row->ascent = it->max_ascent;
 23276           row->height = it->max_ascent + it->max_descent;
 23277           row->phys_ascent = it->max_phys_ascent;
 23278           row->phys_height = it->max_phys_ascent + it->max_phys_descent;
 23279           row->extra_line_spacing = it->max_extra_line_spacing;
 23280         }
 23281 
 23282       /* Compute the width of this line.  */
 23283       row->pixel_width = row->x;
 23284       for (i = 0; i < row->used[TEXT_AREA]; ++i)
 23285         row->pixel_width += row->glyphs[TEXT_AREA][i].pixel_width;
 23286 
 23287       eassert (row->pixel_width >= 0);
 23288       eassert (row->ascent >= 0 && row->height > 0);
 23289 
 23290       row->overlapping_p = (MATRIX_ROW_OVERLAPS_SUCC_P (row)
 23291                             || MATRIX_ROW_OVERLAPS_PRED_P (row));
 23292 
 23293       /* If first line's physical ascent is larger than its logical
 23294          ascent, use the physical ascent, and make the row taller.
 23295          This makes accented characters fully visible.  */
 23296       if (row == MATRIX_FIRST_TEXT_ROW (it->w->desired_matrix)
 23297           && row->phys_ascent > row->ascent)
 23298         {
 23299           row->height += row->phys_ascent - row->ascent;
 23300           row->ascent = row->phys_ascent;
 23301         }
 23302 
 23303       /* Compute how much of the line is visible.  */
 23304       row->visible_height = row->height;
 23305 
 23306       min_y = WINDOW_TAB_LINE_HEIGHT (it->w) + WINDOW_HEADER_LINE_HEIGHT (it->w);
 23307       max_y = WINDOW_BOX_HEIGHT_NO_MODE_LINE (it->w);
 23308 
 23309       if (row->y < min_y)
 23310         row->visible_height -= min_y - row->y;
 23311       if (row->y + row->height > max_y)
 23312         row->visible_height -= row->y + row->height - max_y;
 23313     }
 23314   else
 23315     {
 23316       row->pixel_width = row->used[TEXT_AREA];
 23317       if (row->continued_p)
 23318         row->pixel_width -= it->continuation_pixel_width;
 23319       else if (row->truncated_on_right_p)
 23320         row->pixel_width -= it->truncation_pixel_width;
 23321       row->ascent = row->phys_ascent = 0;
 23322       row->height = row->phys_height = row->visible_height = 1;
 23323       row->extra_line_spacing = 0;
 23324     }
 23325 
 23326   /* Compute a hash code for this row.  */
 23327   row->hash = row_hash (row);
 23328 
 23329   it->max_ascent = it->max_descent = 0;
 23330   it->max_phys_ascent = it->max_phys_descent = 0;
 23331 }
 23332 
 23333 
 23334 static void
 23335 clear_position (struct it *it)
 23336 {
 23337   it->position.charpos = 0;
 23338   it->position.bytepos = 0;
 23339 }
 23340 
 23341 /* Append one space to the glyph row of iterator IT if doing a
 23342    window-based redisplay.  The space has the same face as
 23343    IT->face_id.  Value is true if a space was added.
 23344 
 23345    This function is called to make sure that there is always one glyph
 23346    at the end of a glyph row that the cursor can be set on under
 23347    window-systems.  (If there weren't such a glyph we would not know
 23348    how wide and tall a box cursor should be displayed).
 23349 
 23350    At the same time this space let's a nicely handle clearing to the
 23351    end of the line if the row ends in italic text.  */
 23352 
 23353 static bool
 23354 append_space_for_newline (struct it *it, bool default_face_p)
 23355 {
 23356   int n = it->glyph_row->used[TEXT_AREA];
 23357 
 23358   if (it->glyph_row->glyphs[TEXT_AREA] + n
 23359       < it->glyph_row->glyphs[1 + TEXT_AREA])
 23360     {
 23361       /* Save some values that must not be changed.
 23362          Must save IT->c and IT->len because otherwise
 23363          ITERATOR_AT_END_P wouldn't work anymore after
 23364          append_space_for_newline has been called.  */
 23365       enum display_element_type saved_what = it->what;
 23366       int saved_c = it->c, saved_len = it->len;
 23367       int saved_char_to_display = it->char_to_display;
 23368       int saved_x = it->current_x;
 23369       const int saved_face_id = it->face_id;
 23370       bool saved_box_end = it->end_of_box_run_p;
 23371       struct text_pos saved_pos = it->position;
 23372       Lisp_Object saved_object = it->object;
 23373       struct face *face;
 23374 
 23375       it->what = IT_CHARACTER;
 23376       clear_position (it);
 23377       it->object = Qnil;
 23378       it->len = 1;
 23379 
 23380       int char_width = 1;
 23381 
 23382       if (default_face_p
 23383 #ifdef HAVE_WINDOW_SYSTEM
 23384           || FRAME_WINDOW_P (it->f)
 23385 #endif
 23386           )
 23387         {
 23388           const int local_default_face_id =
 23389             lookup_basic_face (it->w, it->f, DEFAULT_FACE_ID);
 23390 
 23391 #ifdef HAVE_WINDOW_SYSTEM
 23392           if (FRAME_WINDOW_P (it->f))
 23393             {
 23394               struct face *default_face
 23395                 = FACE_FROM_ID (it->f, local_default_face_id);
 23396               struct font *font = (default_face->font
 23397                                    ? default_face->font
 23398                                    : FRAME_FONT (it->f));
 23399               char_width = (font->average_width
 23400                             ? font->average_width
 23401                             : font->space_width);
 23402             }
 23403 #endif
 23404           if (default_face_p)
 23405             it->face_id = local_default_face_id;
 23406         }
 23407       /* Corner case for when display-fill-column-indicator-mode
 23408          is active and the extra character should be added in the
 23409          same place than the line.  */
 23410 
 23411       const int indicator_column =
 23412         fill_column_indicator_column (it, char_width);
 23413       int saved_end_of_box_run = it->end_of_box_run_p;
 23414       bool should_keep_end_of_box_run = false;
 23415 
 23416       if (it->current_x == indicator_column)
 23417         {
 23418           it->c = it->char_to_display
 23419             = XFIXNAT (Vdisplay_fill_column_indicator_character);
 23420           it->face_id
 23421             = merge_faces (it->w, Qfill_column_indicator,
 23422                            0, saved_face_id);
 23423           face = FACE_FROM_ID (it->f, it->face_id);
 23424         }
 23425       else
 23426         {
 23427           it->c = it->char_to_display = ' ';
 23428           /* If the default face was remapped, be sure to use the
 23429              remapped face for the appended newline.  */
 23430 
 23431           face = FACE_FROM_ID (it->f, it->face_id);
 23432           it->face_id = FACE_FOR_CHAR (it->f, face, 0, -1, Qnil);
 23433           /* In R2L rows, we will prepend a stretch glyph that will
 23434              have the end_of_box_run_p flag set for it, so there's no
 23435              need for the appended newline glyph to have that flag
 23436              set.  */
 23437           if (!(it->glyph_row->reversed_p
 23438                 /* But if the appended newline glyph goes all the way to
 23439                    the end of the row, there will be no stretch glyph,
 23440                    so leave the box flag set.  */
 23441                 && saved_x + FRAME_COLUMN_WIDTH (it->f) < it->last_visible_x))
 23442             should_keep_end_of_box_run = true;
 23443         }
 23444       PRODUCE_GLYPHS (it);
 23445       /* Restore the end_of_box_run_p flag which was reset by
 23446          PRODUCE_GLYPHS.  */
 23447       if (should_keep_end_of_box_run)
 23448         it->end_of_box_run_p = saved_end_of_box_run;
 23449 #ifdef HAVE_WINDOW_SYSTEM
 23450       if (FRAME_WINDOW_P (it->f))
 23451         {
 23452           /* Make sure this space glyph has the right ascent and
 23453              descent values, or else cursor at end of line will look
 23454              funny, and height of empty lines will be incorrect.  */
 23455           struct glyph *g = it->glyph_row->glyphs[TEXT_AREA] + n;
 23456           struct font *font = face->font ? face->font : FRAME_FONT (it->f);
 23457           if (n == 0)
 23458             {
 23459               Lisp_Object height, total_height;
 23460               int extra_line_spacing = it->extra_line_spacing;
 23461               int boff = font->baseline_offset;
 23462 
 23463               if (font->vertical_centering)
 23464                 boff = VCENTER_BASELINE_OFFSET (font, it->f) - boff;
 23465 
 23466               it->object = saved_object; /* get_it_property needs this */
 23467               normal_char_ascent_descent (font, -1, &it->ascent, &it->descent);
 23468               /* Must do a subset of line height processing from
 23469                  gui_produce_glyph for newline characters.  */
 23470               height = get_it_property (it, Qline_height);
 23471               if (CONSP (height)
 23472                   && CONSP (XCDR (height))
 23473                   && NILP (XCDR (XCDR (height))))
 23474                 {
 23475                   total_height = XCAR (XCDR (height));
 23476                   height = XCAR (height);
 23477                 }
 23478               else
 23479                 total_height = Qnil;
 23480               height = calc_line_height_property (it, height, font, boff, true);
 23481 
 23482               if (it->override_ascent >= 0)
 23483                 {
 23484                   it->ascent = it->override_ascent;
 23485                   it->descent = it->override_descent;
 23486                   boff = it->override_boff;
 23487                 }
 23488               if (EQ (height, Qt))
 23489                 extra_line_spacing = 0;
 23490               else
 23491                 {
 23492                   Lisp_Object spacing;
 23493 
 23494                   it->phys_ascent = it->ascent;
 23495                   it->phys_descent = it->descent;
 23496                   if (!NILP (height)
 23497                       && XFIXNUM (height) > it->ascent + it->descent)
 23498                     it->ascent = XFIXNUM (height) - it->descent;
 23499 
 23500                   if (!NILP (total_height))
 23501                     spacing = calc_line_height_property (it, total_height, font,
 23502                                                          boff, false);
 23503                   else
 23504                     {
 23505                       spacing = get_it_property (it, Qline_spacing);
 23506                       spacing = calc_line_height_property (it, spacing, font,
 23507                                                            boff, false);
 23508                     }
 23509                   if (FIXNUMP (spacing))
 23510                     {
 23511                       extra_line_spacing = XFIXNUM (spacing);
 23512                       if (!NILP (total_height))
 23513                         extra_line_spacing -= (it->phys_ascent + it->phys_descent);
 23514                     }
 23515                 }
 23516               if (extra_line_spacing > 0)
 23517                 {
 23518                   it->descent += extra_line_spacing;
 23519                   if (extra_line_spacing > it->max_extra_line_spacing)
 23520                     it->max_extra_line_spacing = extra_line_spacing;
 23521                 }
 23522               it->max_ascent = it->ascent;
 23523               it->max_descent = it->descent;
 23524               /* Make sure compute_line_metrics recomputes the row height.  */
 23525               it->glyph_row->height = 0;
 23526             }
 23527 
 23528           g->ascent = it->max_ascent;
 23529           g->descent = it->max_descent;
 23530         }
 23531 #endif /* HAVE_WINDOW_SYSTEM  */
 23532       it->override_ascent = -1;
 23533       it->constrain_row_ascent_descent_p = false;
 23534       it->current_x = saved_x;
 23535       it->object = saved_object;
 23536       it->position = saved_pos;
 23537       it->what = saved_what;
 23538       it->face_id = saved_face_id;
 23539       it->len = saved_len;
 23540       it->c = saved_c;
 23541       it->char_to_display = saved_char_to_display;
 23542       it->end_of_box_run_p = saved_box_end;
 23543       return true;
 23544     }
 23545 
 23546   return false;
 23547 }
 23548 
 23549 
 23550 /* Extend the face of the last glyph in the text area of IT->glyph_row
 23551    to the end of the display line.  Called from display_line.  If the
 23552    glyph row is empty, add a space glyph to it so that we know the
 23553    face to draw.  Set the glyph row flag fill_line_p.  If the glyph
 23554    row is R2L, prepend a stretch glyph to cover the empty space to the
 23555    left of the leftmost glyph.  */
 23556 
 23557 static void
 23558 extend_face_to_end_of_line (struct it *it)
 23559 {
 23560   struct frame *f = it->f;
 23561 
 23562   /* If line is already filled, do nothing.  Non window-system frames
 23563      get a grace of one more ``pixel'' because their characters are
 23564      1-``pixel'' wide, so they hit the equality too early.  This grace
 23565      is needed only for R2L rows that are not continued, to produce
 23566      one extra blank where we could display the cursor.  */
 23567   if ((it->current_x >= it->last_visible_x
 23568        + (!FRAME_WINDOW_P (f)
 23569           && it->glyph_row->reversed_p
 23570           && !it->glyph_row->continued_p))
 23571       /* If the window has display margins, we will need to extend
 23572          their face even if the text area is filled.  */
 23573       && !(WINDOW_LEFT_MARGIN_WIDTH (it->w) > 0
 23574            || WINDOW_RIGHT_MARGIN_WIDTH (it->w) > 0))
 23575     return;
 23576 
 23577   specpdl_ref count = SPECPDL_INDEX ();
 23578 
 23579   /* Don't allow the user to quit out of face-merging code, in case
 23580      this is called when redisplaying a non-selected window, with
 23581      point temporarily moved to window-point.  */
 23582   specbind (Qinhibit_quit, Qt);
 23583   /* The default face, possibly remapped. */
 23584   struct face *default_face =
 23585     FACE_FROM_ID_OR_NULL (f, lookup_basic_face (it->w, f, DEFAULT_FACE_ID));
 23586   if (!default_face)
 23587     return;
 23588 
 23589   const int extend_face_id =
 23590     (it->face_id == default_face->id || it->s != NULL)
 23591     ? it->face_id
 23592     : (it->glyph_row->ends_at_zv_p
 23593        ? default_face->id
 23594        : face_at_pos (it, LFACE_EXTEND_INDEX));
 23595   unbind_to (count, Qnil);
 23596 
 23597   /* Face extension extends the background and box of IT->extend_face_id
 23598      to the end of the line.  If the background equals the background
 23599      of the frame, we don't have to do anything.  */
 23600   struct face *face = FACE_FROM_ID (f, (it->face_before_selective_p
 23601                                         ? it->saved_face_id
 23602                                         : extend_face_id));
 23603 
 23604   if (FRAME_WINDOW_P (f)
 23605       && MATRIX_ROW_DISPLAYS_TEXT_P (it->glyph_row)
 23606       && face->box == FACE_NO_BOX
 23607       && face->underline == FACE_NO_UNDERLINE
 23608       && !face->overline_p
 23609       && !face->strike_through_p
 23610       && face->background == FRAME_BACKGROUND_PIXEL (f)
 23611 #ifdef HAVE_WINDOW_SYSTEM
 23612       && !face->stipple
 23613 #endif
 23614       && !it->glyph_row->reversed_p
 23615       && !display_fill_column_indicator)
 23616     return;
 23617 
 23618   /* Set the glyph row flag indicating that the face of the last glyph
 23619      in the text area has to be drawn to the end of the text area.  */
 23620   it->glyph_row->fill_line_p = true;
 23621 
 23622   const int orig_face_id = it->face_id;
 23623   /* If current character of IT is not ASCII, make sure we have the
 23624      ASCII face.  This will be automatically undone the next time
 23625      get_next_display_element returns a multibyte character.  Note
 23626      that the character will always be single byte in unibyte
 23627      text.  */
 23628   if (!ASCII_CHAR_P (it->c))
 23629     it->face_id = FACE_FOR_CHAR (f, face, 0, -1, Qnil);
 23630 
 23631 
 23632 #ifdef HAVE_WINDOW_SYSTEM
 23633   if (FRAME_WINDOW_P (f))
 23634     {
 23635       /* If the row is empty, add a space with the current face of IT,
 23636          so that we know which face to draw.  */
 23637       if (it->glyph_row->used[TEXT_AREA] == 0)
 23638         {
 23639           it->glyph_row->glyphs[TEXT_AREA][0] = space_glyph;
 23640           it->glyph_row->glyphs[TEXT_AREA][0].face_id = face->id;
 23641           it->glyph_row->used[TEXT_AREA] = 1;
 23642         }
 23643       /* Mode line and the header line don't have margins, and
 23644          likewise the frame's tool-bar window, if there is any.  */
 23645       if (!(it->glyph_row->mode_line_p
 23646             || (WINDOWP (f->tab_bar_window)
 23647                 && it->w == XWINDOW (f->tab_bar_window))
 23648 #ifndef HAVE_EXT_TOOL_BAR
 23649             || (WINDOWP (f->tool_bar_window)
 23650                 && it->w == XWINDOW (f->tool_bar_window))
 23651 #endif
 23652             ))
 23653         {
 23654           if (WINDOW_LEFT_MARGIN_WIDTH (it->w) > 0
 23655               && it->glyph_row->used[LEFT_MARGIN_AREA] == 0)
 23656             {
 23657               it->glyph_row->glyphs[LEFT_MARGIN_AREA][0] = space_glyph;
 23658               it->glyph_row->glyphs[LEFT_MARGIN_AREA][0].face_id =
 23659                 default_face->id;
 23660               it->glyph_row->used[LEFT_MARGIN_AREA] = 1;
 23661             }
 23662           if (WINDOW_RIGHT_MARGIN_WIDTH (it->w) > 0
 23663               && it->glyph_row->used[RIGHT_MARGIN_AREA] == 0)
 23664             {
 23665               it->glyph_row->glyphs[RIGHT_MARGIN_AREA][0] = space_glyph;
 23666               it->glyph_row->glyphs[RIGHT_MARGIN_AREA][0].face_id =
 23667                 default_face->id;
 23668               it->glyph_row->used[RIGHT_MARGIN_AREA] = 1;
 23669             }
 23670 
 23671           struct font *font = (default_face->font
 23672                                ? default_face->font
 23673                                : FRAME_FONT (f));
 23674 
 23675           const int char_width = (font->average_width
 23676                                   ? font->average_width
 23677                                   : font->space_width);
 23678 
 23679           const int indicator_column =
 23680             fill_column_indicator_column (it, char_width);
 23681 
 23682           const char saved_char = it->char_to_display;
 23683           const struct text_pos saved_pos = it->position;
 23684           const bool saved_avoid_cursor = it->avoid_cursor_p;
 23685           const bool saved_box_start = it->start_of_box_run_p;
 23686           Lisp_Object save_object = it->object;
 23687           const int saved_face_id = it->face_id;
 23688 
 23689           it->face_id = extend_face_id;
 23690           it->avoid_cursor_p = true;
 23691           it->object = Qnil;
 23692 
 23693           const int stretch_height = it->ascent + it->descent;
 23694           const int stretch_ascent =
 23695             (stretch_height * FONT_BASE (font)) / FONT_HEIGHT (font);
 23696 
 23697           if (indicator_column >= 0
 23698               && indicator_column > it->current_x
 23699               && indicator_column < it->last_visible_x)
 23700             {
 23701 
 23702               /* Here we subtract char_width because we want the
 23703                  column indicator in the column INDICATOR_COLUMN,
 23704                  not after it.  */
 23705               const int stretch_width =
 23706                 indicator_column - it->current_x - char_width;
 23707 
 23708               clear_position (it);
 23709 
 23710               /* Only generate a stretch glyph if there is distance
 23711                  between current_x and the indicator position.  */
 23712               if (stretch_width > 0)
 23713                 {
 23714                   append_stretch_glyph (it, Qnil, stretch_width,
 23715                                         stretch_height, stretch_ascent);
 23716                 }
 23717 
 23718               /* Generate the glyph indicator only if
 23719                  append_space_for_newline didn't already.  */
 23720               if (it->current_x < indicator_column)
 23721                 {
 23722                   const int save_face_id = it->face_id;
 23723                   const int save_ascent = it->ascent;
 23724                   const int save_descent = it->descent;
 23725                   it->char_to_display
 23726                     = XFIXNAT (Vdisplay_fill_column_indicator_character);
 23727                   it->face_id
 23728                     = merge_faces (it->w, Qfill_column_indicator,
 23729                                    0, extend_face_id);
 23730                   PRODUCE_GLYPHS (it);
 23731                   it->face_id = save_face_id;
 23732                   it->ascent = save_ascent;
 23733                   it->descent = save_descent;
 23734                 }
 23735             }
 23736 
 23737           /* Fill space until window edge with the merged face.  Do that
 23738              only for L2R rows, as R2L rows are handled specially below.  */
 23739           if (!it->glyph_row->reversed_p)
 23740             {
 23741               const int stretch_width = it->last_visible_x - it->current_x;
 23742 
 23743               if (stretch_width > 0)
 23744                 {
 23745                   clear_position (it);
 23746                   append_stretch_glyph (it, Qnil, stretch_width,
 23747                                         stretch_height, stretch_ascent);
 23748                 }
 23749             }
 23750 
 23751           it->char_to_display = saved_char;
 23752           it->position = saved_pos;
 23753           it->avoid_cursor_p = saved_avoid_cursor;
 23754           it->start_of_box_run_p = saved_box_start;
 23755           it->object = save_object;
 23756           it->face_id = saved_face_id;
 23757         }
 23758       if (it->glyph_row->reversed_p)
 23759         {
 23760           /* Prepend a stretch glyph to the row, such that the
 23761              rightmost glyph will be drawn flushed all the way to the
 23762              right margin of the window.  The stretch glyph that will
 23763              occupy the empty space, if any, to the left of the
 23764              glyph.  */
 23765           struct font *font = face->font ? face->font : FRAME_FONT (f);
 23766           struct glyph *row_start = it->glyph_row->glyphs[TEXT_AREA];
 23767           struct glyph *row_end = row_start + it->glyph_row->used[TEXT_AREA];
 23768           struct glyph *g;
 23769           int row_width, stretch_ascent, stretch_width;
 23770           struct text_pos saved_pos;
 23771           int saved_face_id;
 23772           bool saved_avoid_cursor, saved_box_start;
 23773 
 23774           for (row_width = 0, g = row_start; g < row_end; g++)
 23775             row_width += g->pixel_width;
 23776 
 23777           /* FIXME: There are various minor display glitches in R2L
 23778              rows when only one of the fringes is missing.  The
 23779              strange condition below produces the least bad effect.  */
 23780           if ((WINDOW_LEFT_FRINGE_WIDTH (it->w) == 0)
 23781               == (WINDOW_RIGHT_FRINGE_WIDTH (it->w) == 0)
 23782               || WINDOW_RIGHT_FRINGE_WIDTH (it->w) != 0)
 23783             stretch_width = window_box_width (it->w, TEXT_AREA);
 23784           else
 23785             stretch_width = it->last_visible_x - it->first_visible_x;
 23786           stretch_width -= row_width;
 23787 
 23788           if (stretch_width > 0)
 23789             {
 23790               stretch_ascent =
 23791                 (((it->ascent + it->descent)
 23792                   * FONT_BASE (font)) / FONT_HEIGHT (font));
 23793               saved_pos = it->position;
 23794               clear_position (it);
 23795               saved_avoid_cursor = it->avoid_cursor_p;
 23796               it->avoid_cursor_p = true;
 23797               saved_face_id = it->face_id;
 23798               saved_box_start = it->start_of_box_run_p;
 23799               /* The last row's stretch glyph should get the default
 23800                  face, to avoid painting the rest of the window with
 23801                  the region face, if the region ends at ZV.  */
 23802               it->face_id = (it->glyph_row->ends_at_zv_p ?
 23803                              default_face->id : face->id);
 23804 
 23805               it->start_of_box_run_p = false;
 23806               append_stretch_glyph (it, Qnil, stretch_width,
 23807                                     it->ascent + it->descent, stretch_ascent);
 23808               it->position = saved_pos;
 23809               it->avoid_cursor_p = saved_avoid_cursor;
 23810               it->face_id = saved_face_id;
 23811               it->start_of_box_run_p = saved_box_start;
 23812             }
 23813           /* If stretch_width comes out negative, it means that the
 23814              last glyph is only partially visible.  In R2L rows, we
 23815              want the leftmost glyph to be partially visible, so we
 23816              need to give the row the corresponding left offset.  */
 23817           if (stretch_width < 0)
 23818             it->glyph_row->x = stretch_width;
 23819         }
 23820       it->face_id = orig_face_id;
 23821     }
 23822   else
 23823 #endif  /* HAVE_WINDOW_SYSTEM */
 23824     {
 23825       /* Save some values that must not be changed.  */
 23826       int saved_x = it->current_x;
 23827       struct text_pos saved_pos = it->position;
 23828       Lisp_Object saved_object = it->object;;
 23829       enum display_element_type saved_what = it->what;
 23830 
 23831       it->what = IT_CHARACTER;
 23832       clear_position (it);
 23833       it->object = Qnil;
 23834       it->c = it->char_to_display = ' ';
 23835       it->len = 1;
 23836 
 23837       if (WINDOW_LEFT_MARGIN_WIDTH (it->w) > 0
 23838           && (it->glyph_row->used[LEFT_MARGIN_AREA]
 23839               < WINDOW_LEFT_MARGIN_WIDTH (it->w))
 23840           && !it->glyph_row->mode_line_p
 23841           && face->background != FRAME_BACKGROUND_PIXEL (f))
 23842         {
 23843           struct glyph *g = it->glyph_row->glyphs[LEFT_MARGIN_AREA];
 23844           struct glyph *e = g + it->glyph_row->used[LEFT_MARGIN_AREA];
 23845 
 23846           for (it->current_x = 0; g < e; g++)
 23847             it->current_x += g->pixel_width;
 23848 
 23849           it->area = LEFT_MARGIN_AREA;
 23850           it->face_id = default_face->id;
 23851           while (it->glyph_row->used[LEFT_MARGIN_AREA]
 23852                  < WINDOW_LEFT_MARGIN_WIDTH (it->w)
 23853                  && g < it->glyph_row->glyphs[TEXT_AREA])
 23854             {
 23855               PRODUCE_GLYPHS (it);
 23856               /* term.c:produce_glyphs advances it->current_x only for
 23857                  TEXT_AREA.  */
 23858               it->current_x += it->pixel_width;
 23859               g++;
 23860             }
 23861 
 23862           it->current_x = saved_x;
 23863           it->area = TEXT_AREA;
 23864         }
 23865 
 23866       /* The last row's blank glyphs should get the default face, to
 23867          avoid painting the rest of the window with the region face,
 23868          if the region ends at ZV.  */
 23869       it->face_id = (it->glyph_row->ends_at_zv_p ?
 23870                      default_face->id : face->id);
 23871 
 23872       /* Make sure our idea of current_x is in sync with the glyphs
 23873          actually in the glyph row.  They might differ because
 23874          append_space_for_newline can insert one glyph without
 23875          updating current_x.  */
 23876       it->current_x = it->glyph_row->used[TEXT_AREA];
 23877 
 23878       /* The above assignment causes the code below to use a
 23879          non-standard semantics of it->current_x: it is measured
 23880          relative to the beginning of the text-area, thus disregarding
 23881          the window's hscroll.  That is why we need to correct the
 23882          indicator column for the hscroll, otherwise the indicator
 23883          will not move together with the text as result of horizontal
 23884          scrolling.  */
 23885       const int indicator_column =
 23886         fill_column_indicator_column (it, 1) - it->first_visible_x;
 23887 
 23888       /* Display fill-column indicator if needed.  */
 23889       while (it->current_x <= it->last_visible_x)
 23890         {
 23891           if (it->current_x != indicator_column)
 23892             PRODUCE_GLYPHS (it);
 23893           else
 23894             {
 23895               int saved_face_id = it->face_id;
 23896               it->face_id
 23897                 = merge_faces (it->w, Qfill_column_indicator, 0, extend_face_id);
 23898               it->c = it->char_to_display
 23899                 = XFIXNAT (Vdisplay_fill_column_indicator_character);
 23900 
 23901               PRODUCE_GLYPHS (it);
 23902 
 23903               it->face_id = saved_face_id;
 23904               it->c = it->char_to_display = ' ';
 23905             }
 23906         }
 23907 
 23908       if (WINDOW_RIGHT_MARGIN_WIDTH (it->w) > 0
 23909           && (it->glyph_row->used[RIGHT_MARGIN_AREA]
 23910               < WINDOW_RIGHT_MARGIN_WIDTH (it->w))
 23911           && !it->glyph_row->mode_line_p
 23912           && face->background != FRAME_BACKGROUND_PIXEL (f))
 23913         {
 23914           struct glyph *g = it->glyph_row->glyphs[RIGHT_MARGIN_AREA];
 23915           struct glyph *e = g + it->glyph_row->used[RIGHT_MARGIN_AREA];
 23916 
 23917           for ( ; g < e; g++)
 23918             it->current_x += g->pixel_width;
 23919 
 23920           it->area = RIGHT_MARGIN_AREA;
 23921           it->face_id = default_face->id;
 23922           while (it->glyph_row->used[RIGHT_MARGIN_AREA]
 23923                  < WINDOW_RIGHT_MARGIN_WIDTH (it->w)
 23924                  && g < it->glyph_row->glyphs[LAST_AREA])
 23925             {
 23926               PRODUCE_GLYPHS (it);
 23927               it->current_x += it->pixel_width;
 23928               g++;
 23929             }
 23930 
 23931           it->area = TEXT_AREA;
 23932         }
 23933 
 23934       /* Don't count these blanks really.  It would let us insert a left
 23935          truncation glyph below and make us set the cursor on them, maybe.  */
 23936       it->current_x = saved_x;
 23937       it->object = saved_object;
 23938       it->position = saved_pos;
 23939       it->what = saved_what;
 23940       it->face_id = orig_face_id;
 23941     }
 23942 }
 23943 
 23944 
 23945 /* Value is true if text starting at CHARPOS in current_buffer is
 23946    trailing whitespace.  */
 23947 
 23948 static bool
 23949 trailing_whitespace_p (ptrdiff_t charpos)
 23950 {
 23951   ptrdiff_t bytepos = CHAR_TO_BYTE (charpos);
 23952   int c = 0;
 23953 
 23954   while (bytepos < ZV_BYTE
 23955          && (c = FETCH_BYTE (bytepos),
 23956              c == ' ' || c == '\t'))
 23957     ++bytepos;
 23958 
 23959   if (bytepos >= ZV_BYTE || c == '\n' || c == '\r')
 23960     {
 23961       if (bytepos != PT_BYTE)
 23962         return true;
 23963     }
 23964   return false;
 23965 }
 23966 
 23967 
 23968 /* Highlight trailing whitespace, if any, in row at IT.  */
 23969 
 23970 static void
 23971 highlight_trailing_whitespace (struct it *it)
 23972 {
 23973   struct glyph_row *row = it->glyph_row;
 23974   int used = row->used[TEXT_AREA];
 23975 
 23976   if (used)
 23977     {
 23978       struct glyph *start = row->glyphs[TEXT_AREA];
 23979       struct glyph *glyph = start + used - 1;
 23980 
 23981       if (row->reversed_p)
 23982         {
 23983           /* Right-to-left rows need to be processed in the opposite
 23984              direction, so swap the edge pointers. */
 23985           glyph = start;
 23986           start = row->glyphs[TEXT_AREA] + used - 1;
 23987         }
 23988 
 23989       /* Skip over glyphs inserted to display the cursor at the
 23990          end of a line, for extending the face of the last glyph
 23991          to the end of the line on terminals, and for truncation
 23992          and continuation glyphs.  */
 23993       if (!row->reversed_p)
 23994         {
 23995           while (glyph >= start
 23996                  && (glyph->type == CHAR_GLYPH
 23997                      || glyph->type == STRETCH_GLYPH)
 23998                  && NILP (glyph->object))
 23999             --glyph;
 24000         }
 24001       else
 24002         {
 24003           while (glyph <= start
 24004                  && (glyph->type == CHAR_GLYPH || glyph->type == STRETCH_GLYPH)
 24005                  && NILP (glyph->object))
 24006             ++glyph;
 24007         }
 24008 
 24009       /* If last glyph is a space or stretch, and it's trailing
 24010          whitespace, set the face of all trailing whitespace glyphs in
 24011          IT->glyph_row to `trailing-whitespace'.  */
 24012       if ((row->reversed_p ? glyph <= start : glyph >= start)
 24013           && BUFFERP (glyph->object)
 24014           && (glyph->type == STRETCH_GLYPH
 24015               || (glyph->type == CHAR_GLYPH
 24016                   && glyph->u.ch == ' '))
 24017           && trailing_whitespace_p (glyph->charpos))
 24018         {
 24019           int face_id = lookup_named_face (it->w, it->f, Qtrailing_whitespace, false);
 24020           if (face_id < 0)
 24021             return;
 24022 
 24023           if (!row->reversed_p)
 24024             {
 24025               while (glyph >= start
 24026                      && BUFFERP (glyph->object)
 24027                      && (glyph->type == STRETCH_GLYPH
 24028                          || (glyph->type == CHAR_GLYPH
 24029                              && glyph->u.ch == ' ')))
 24030                 (glyph--)->face_id = face_id;
 24031             }
 24032           else
 24033             {
 24034               while (glyph <= start
 24035                      && BUFFERP (glyph->object)
 24036                      && (glyph->type == STRETCH_GLYPH
 24037                          || (glyph->type == CHAR_GLYPH
 24038                              && glyph->u.ch == ' ')))
 24039                 (glyph++)->face_id = face_id;
 24040             }
 24041         }
 24042     }
 24043 }
 24044 
 24045 
 24046 /* Value is true if glyph row ROW should be
 24047    considered to hold the buffer position CHARPOS.  */
 24048 
 24049 static bool
 24050 row_for_charpos_p (struct glyph_row *row, ptrdiff_t charpos)
 24051 {
 24052   bool result = true;
 24053 
 24054   if (charpos == CHARPOS (row->end.pos)
 24055       || charpos == MATRIX_ROW_END_CHARPOS (row))
 24056     {
 24057       /* Suppose the row ends on a string.
 24058          Unless the row is continued, that means it ends on a newline
 24059          in the string.  If it's anything other than a display string
 24060          (e.g., a before-string from an overlay), we don't want the
 24061          cursor there.  (This heuristic seems to give the optimal
 24062          behavior for the various types of multi-line strings.)
 24063          One exception: if the string has `cursor' property on one of
 24064          its characters, we _do_ want the cursor there.  */
 24065       if (CHARPOS (row->end.string_pos) >= 0)
 24066         {
 24067           if (row->continued_p)
 24068             result = true;
 24069           else
 24070             {
 24071               /* Check for `display' property.  */
 24072               struct glyph *beg = row->glyphs[TEXT_AREA];
 24073               struct glyph *end = beg + row->used[TEXT_AREA] - 1;
 24074               struct glyph *glyph;
 24075 
 24076               result = false;
 24077               for (glyph = end; glyph >= beg; --glyph)
 24078                 if (STRINGP (glyph->object))
 24079                   {
 24080                     Lisp_Object prop
 24081                       = Fget_char_property (make_fixnum (charpos),
 24082                                             Qdisplay, Qnil);
 24083                     result =
 24084                       (!NILP (prop)
 24085                        && display_prop_string_p (prop, glyph->object));
 24086                     /* If there's a `cursor' property on one of the
 24087                        string's characters, this row is a cursor row,
 24088                        even though this is not a display string.  */
 24089                     if (!result)
 24090                       {
 24091                         Lisp_Object s = glyph->object;
 24092 
 24093                         for ( ; glyph >= beg && EQ (glyph->object, s); --glyph)
 24094                           {
 24095                             ptrdiff_t gpos = glyph->charpos;
 24096 
 24097                             if (!NILP (Fget_char_property (make_fixnum (gpos),
 24098                                                            Qcursor, s)))
 24099                               {
 24100                                 result = true;
 24101                                 break;
 24102                               }
 24103                           }
 24104                       }
 24105                     break;
 24106                   }
 24107             }
 24108         }
 24109       else if (MATRIX_ROW_ENDS_IN_MIDDLE_OF_CHAR_P (row))
 24110         {
 24111           /* If the row ends in middle of a real character,
 24112              and the line is continued, we want the cursor here.
 24113              That's because CHARPOS (ROW->end.pos) would equal
 24114              PT if PT is before the character.  */
 24115           if (!row->ends_in_ellipsis_p)
 24116             result = row->continued_p;
 24117           else
 24118           /* If the row ends in an ellipsis, then
 24119              CHARPOS (ROW->end.pos) will equal point after the
 24120              invisible text.  We want that position to be displayed
 24121              after the ellipsis.  */
 24122             result = false;
 24123         }
 24124       /* If the row ends at ZV, display the cursor at the end of that
 24125          row instead of at the start of the row below.  */
 24126       else
 24127         result = row->ends_at_zv_p;
 24128     }
 24129 
 24130   return result;
 24131 }
 24132 
 24133 /* Value is true if glyph row ROW should be
 24134    used to hold the cursor.  */
 24135 
 24136 static bool
 24137 cursor_row_p (struct glyph_row *row)
 24138 {
 24139   return row_for_charpos_p (row, PT);
 24140 }
 24141 
 24142 
 24143 
 24144 /* Push the property PROP so that it will be rendered at the current
 24145    position in IT.  Return true if PROP was successfully pushed, false
 24146    otherwise.  Called from handle_line_prefix to handle the
 24147    `line-prefix' and `wrap-prefix' properties.  */
 24148 
 24149 static bool
 24150 push_prefix_prop (struct it *it, Lisp_Object prop)
 24151 {
 24152   struct text_pos pos =
 24153     STRINGP (it->string) ? it->current.string_pos : it->current.pos;
 24154 
 24155   eassert (it->method == GET_FROM_BUFFER
 24156            || it->method == GET_FROM_DISPLAY_VECTOR
 24157            || it->method == GET_FROM_STRING
 24158            || it->method == GET_FROM_IMAGE);
 24159 
 24160   /* We need to save the current buffer/string position, so it will be
 24161      restored by pop_it, because iterate_out_of_display_property
 24162      depends on that being set correctly, but some situations leave
 24163      it->position not yet set when this function is called.  */
 24164   push_it (it, &pos);
 24165 
 24166   if (STRINGP (prop))
 24167     {
 24168       if (SCHARS (prop) == 0)
 24169         {
 24170           pop_it (it);
 24171           return false;
 24172         }
 24173 
 24174       it->string = prop;
 24175       it->string_from_prefix_prop_p = true;
 24176       it->multibyte_p = STRING_MULTIBYTE (it->string);
 24177       it->current.overlay_string_index = -1;
 24178       IT_STRING_CHARPOS (*it) = IT_STRING_BYTEPOS (*it) = 0;
 24179       it->end_charpos = it->string_nchars = SCHARS (it->string);
 24180       it->method = GET_FROM_STRING;
 24181       it->stop_charpos = 0;
 24182       it->prev_stop = 0;
 24183       it->base_level_stop = 0;
 24184       it->cmp_it.id = -1;
 24185 
 24186       /* Force paragraph direction to be that of the parent
 24187          buffer/string.  */
 24188       if (it->bidi_p && it->bidi_it.paragraph_dir == R2L)
 24189         it->paragraph_embedding = it->bidi_it.paragraph_dir;
 24190       else
 24191         it->paragraph_embedding = L2R;
 24192 
 24193       /* Set up the bidi iterator for this display string.  */
 24194       if (it->bidi_p)
 24195         {
 24196           it->bidi_it.string.lstring = it->string;
 24197           it->bidi_it.string.s = NULL;
 24198           it->bidi_it.string.schars = it->end_charpos;
 24199           it->bidi_it.string.bufpos = IT_CHARPOS (*it);
 24200           it->bidi_it.string.from_disp_str = it->string_from_display_prop_p;
 24201           it->bidi_it.string.unibyte = !it->multibyte_p;
 24202           it->bidi_it.w = it->w;
 24203           bidi_init_it (0, 0, FRAME_WINDOW_P (it->f), &it->bidi_it);
 24204         }
 24205     }
 24206   else if (CONSP (prop) && EQ (XCAR (prop), Qspace))
 24207     {
 24208       it->method = GET_FROM_STRETCH;
 24209       it->object = prop;
 24210     }
 24211 #ifdef HAVE_WINDOW_SYSTEM
 24212   else if (IMAGEP (prop))
 24213     {
 24214       it->what = IT_IMAGE;
 24215       it->image_id = lookup_image (it->f, prop, it->face_id);
 24216       it->method = GET_FROM_IMAGE;
 24217     }
 24218 #endif /* HAVE_WINDOW_SYSTEM */
 24219   else
 24220     {
 24221       pop_it (it);              /* bogus display property, give up */
 24222       return false;
 24223     }
 24224 
 24225   return true;
 24226 }
 24227 
 24228 /* Return the character-property PROP at the current position in IT.  */
 24229 
 24230 static Lisp_Object
 24231 get_it_property (struct it *it, Lisp_Object prop)
 24232 {
 24233   Lisp_Object position, object = it->object;
 24234 
 24235   if (STRINGP (object))
 24236     position = make_fixnum (IT_STRING_CHARPOS (*it));
 24237   else if (BUFFERP (object))
 24238     {
 24239       position = make_fixnum (IT_CHARPOS (*it));
 24240       object = it->window;
 24241     }
 24242   else
 24243     return Qnil;
 24244 
 24245   return Fget_char_property (position, prop, object);
 24246 }
 24247 
 24248 /* Return the line-prefix/wrap-prefix property, checking both the
 24249    current IT->OBJECT and the underlying buffer text.  */
 24250 
 24251 static Lisp_Object
 24252 get_line_prefix_it_property (struct it *it, Lisp_Object prop)
 24253 {
 24254   Lisp_Object prefix = get_it_property (it, prop);
 24255 
 24256   /* If we are looking at a display or overlay string, check also the
 24257      underlying buffer text.  */
 24258   if (NILP (prefix) && it->sp > 0 && STRINGP (it->object))
 24259     return Fget_char_property (make_fixnum (IT_CHARPOS (*it)), prop,
 24260                                it->w->contents);
 24261   return prefix;
 24262 }
 24263 
 24264 /* See if there's a line- or wrap-prefix, and if so, push it on IT.  */
 24265 
 24266 static void
 24267 handle_line_prefix (struct it *it)
 24268 {
 24269   Lisp_Object prefix;
 24270 
 24271   if (it->continuation_lines_width > 0)
 24272     {
 24273       prefix = get_line_prefix_it_property (it, Qwrap_prefix);
 24274       if (NILP (prefix))
 24275         prefix = Vwrap_prefix;
 24276     }
 24277   else
 24278     {
 24279       prefix = get_line_prefix_it_property (it, Qline_prefix);
 24280       if (NILP (prefix))
 24281         prefix = Vline_prefix;
 24282     }
 24283   if (! NILP (prefix) && push_prefix_prop (it, prefix))
 24284     {
 24285       /* If the prefix is wider than the window, and we try to wrap
 24286          it, it would acquire its own wrap prefix, and so on till the
 24287          iterator stack overflows.  So, don't wrap the prefix.  */
 24288       it->line_wrap = TRUNCATE;
 24289       it->avoid_cursor_p = true;
 24290     }
 24291 }
 24292 
 24293 
 24294 
 24295 /* Remove N glyphs at the start of a reversed IT->glyph_row.  Called
 24296    only for R2L lines from display_line and display_string, when they
 24297    decide that too many glyphs were produced by PRODUCE_GLYPHS, and
 24298    the line/string needs to be continued on the next glyph row.  */
 24299 static void
 24300 unproduce_glyphs (struct it *it, int n)
 24301 {
 24302   struct glyph *glyph, *end;
 24303 
 24304   eassert (it->glyph_row);
 24305   eassert (it->glyph_row->reversed_p);
 24306   eassert (it->area == TEXT_AREA);
 24307   eassert (n <= it->glyph_row->used[TEXT_AREA]);
 24308 
 24309   if (n > it->glyph_row->used[TEXT_AREA])
 24310     n = it->glyph_row->used[TEXT_AREA];
 24311   glyph = it->glyph_row->glyphs[TEXT_AREA] + n;
 24312   end = it->glyph_row->glyphs[TEXT_AREA] + it->glyph_row->used[TEXT_AREA];
 24313   for ( ; glyph < end; glyph++)
 24314     glyph[-n] = *glyph;
 24315 }
 24316 
 24317 /* Find the positions in a bidi-reordered ROW to serve as ROW->minpos
 24318    and ROW->maxpos.  */
 24319 static void
 24320 find_row_edges (struct it *it, struct glyph_row *row,
 24321                 ptrdiff_t min_pos, ptrdiff_t min_bpos,
 24322                 ptrdiff_t max_pos, ptrdiff_t max_bpos)
 24323 {
 24324   /* FIXME: Revisit this when glyph ``spilling'' in continuation
 24325      lines' rows is implemented for bidi-reordered rows.  */
 24326 
 24327   /* ROW->minpos is the value of min_pos, the minimal buffer position
 24328      we have in ROW, or ROW->start.pos if that is smaller.  */
 24329   if (min_pos <= ZV && min_pos < row->start.pos.charpos)
 24330     SET_TEXT_POS (row->minpos, min_pos, min_bpos);
 24331   else
 24332     /* We didn't find buffer positions smaller than ROW->start, or
 24333        didn't find _any_ valid buffer positions in any of the glyphs,
 24334        so we must trust the iterator's computed positions.  */
 24335       row->minpos = row->start.pos;
 24336   if (max_pos <= 0)
 24337     {
 24338       max_pos = CHARPOS (it->current.pos);
 24339       max_bpos = BYTEPOS (it->current.pos);
 24340     }
 24341 
 24342   /* Here are the various use-cases for ending the row, and the
 24343      corresponding values for ROW->maxpos:
 24344 
 24345      Line ends in a newline from buffer       eol_pos + 1
 24346      Line is continued from buffer            max_pos + 1
 24347      Line is truncated on right               it->current.pos
 24348      Line ends in a newline from string       max_pos + 1(*)
 24349       (*) + 1 only when line ends in a forward scan
 24350      Line is continued from string            max_pos
 24351      Line is continued from display vector    max_pos
 24352      Line is entirely from a string           min_pos == max_pos
 24353      Line is entirely from a display vector   min_pos == max_pos
 24354      Line that ends at ZV                     ZV
 24355 
 24356      If you discover other use-cases, please add them here as
 24357      appropriate.  */
 24358   if (row->ends_at_zv_p)
 24359     row->maxpos = it->current.pos;
 24360   else if (row->used[TEXT_AREA])
 24361     {
 24362       bool seen_this_string = false;
 24363       struct glyph_row *r1 = row - 1;
 24364 
 24365       /* Did we see the same display string on the previous row?  */
 24366       if (STRINGP (it->object)
 24367           /* this is not the first row */
 24368           && row > it->w->desired_matrix->rows
 24369           /* previous row is not the header line or tab-line */
 24370           && !r1->mode_line_p
 24371           /* previous row also ends in a newline from a string */
 24372           && r1->ends_in_newline_from_string_p)
 24373         {
 24374           struct glyph *start, *end;
 24375 
 24376           /* Search for the last glyph of the previous row that came
 24377              from buffer or string.  Depending on whether the row is
 24378              L2R or R2L, we need to process it front to back or the
 24379              other way round.  */
 24380           if (!r1->reversed_p)
 24381             {
 24382               start = r1->glyphs[TEXT_AREA];
 24383               end = start + r1->used[TEXT_AREA];
 24384               /* Glyphs inserted by redisplay have nil as their object.  */
 24385               while (end > start
 24386                      && NILP ((end - 1)->object)
 24387                      && (end - 1)->charpos <= 0)
 24388                 --end;
 24389               if (end > start)
 24390                 {
 24391                   if (EQ ((end - 1)->object, it->object))
 24392                     seen_this_string = true;
 24393                 }
 24394               else
 24395                 /* If all the glyphs of the previous row were inserted
 24396                    by redisplay, it means the previous row was
 24397                    produced from a single newline, which is only
 24398                    possible if that newline came from the same string
 24399                    as the one which produced this ROW.  */
 24400                 seen_this_string = true;
 24401             }
 24402           else
 24403             {
 24404               end = r1->glyphs[TEXT_AREA] - 1;
 24405               start = end + r1->used[TEXT_AREA];
 24406               while (end < start
 24407                      && NILP ((end + 1)->object)
 24408                      && (end + 1)->charpos <= 0)
 24409                 ++end;
 24410               if (end < start)
 24411                 {
 24412                   if (EQ ((end + 1)->object, it->object))
 24413                     seen_this_string = true;
 24414                 }
 24415               else
 24416                 seen_this_string = true;
 24417             }
 24418         }
 24419       /* Take note of each display string that covers a newline only
 24420          once, the first time we see it.  This is for when a display
 24421          string includes more than one newline in it.  */
 24422       if (row->ends_in_newline_from_string_p && !seen_this_string)
 24423         {
 24424           /* If we were scanning the buffer forward when we displayed
 24425              the string, we want to account for at least one buffer
 24426              position that belongs to this row (position covered by
 24427              the display string), so that cursor positioning will
 24428              consider this row as a candidate when point is at the end
 24429              of the visual line represented by this row.  This is not
 24430              required when scanning back, because max_pos will already
 24431              have a much larger value.  */
 24432           if (CHARPOS (row->end.pos) > max_pos)
 24433             inc_both (&max_pos, &max_bpos);
 24434           SET_TEXT_POS (row->maxpos, max_pos, max_bpos);
 24435         }
 24436       else if (CHARPOS (it->eol_pos) > 0)
 24437         SET_TEXT_POS (row->maxpos,
 24438                       CHARPOS (it->eol_pos) + 1, BYTEPOS (it->eol_pos) + 1);
 24439       else if (row->continued_p)
 24440         {
 24441           /* If max_pos is different from IT's current position, it
 24442              means IT->method does not belong to the display element
 24443              at max_pos.  However, it also means that the display
 24444              element at max_pos was displayed in its entirety on this
 24445              line, which is equivalent to saying that the next line
 24446              starts at the next buffer position.  */
 24447           if (IT_CHARPOS (*it) == max_pos && it->method != GET_FROM_BUFFER)
 24448             SET_TEXT_POS (row->maxpos, max_pos, max_bpos);
 24449           else
 24450             {
 24451               inc_both (&max_pos, &max_bpos);
 24452               SET_TEXT_POS (row->maxpos, max_pos, max_bpos);
 24453             }
 24454         }
 24455       else if (row->truncated_on_right_p)
 24456         /* display_line already called reseat_at_next_visible_line_start,
 24457            which puts the iterator at the beginning of the next line, in
 24458            the logical order. */
 24459         row->maxpos = it->current.pos;
 24460       else if (max_pos == min_pos && it->method != GET_FROM_BUFFER)
 24461         /* A line that is entirely from a string/image/stretch...  */
 24462         row->maxpos = row->minpos;
 24463       else
 24464         emacs_abort ();
 24465     }
 24466   else
 24467     row->maxpos = it->current.pos;
 24468 }
 24469 
 24470 /* Like display_count_lines, but capable of counting outside of the
 24471    current narrowed region.  */
 24472 static ptrdiff_t
 24473 display_count_lines_logically (ptrdiff_t start_byte, ptrdiff_t limit_byte,
 24474                                ptrdiff_t count, ptrdiff_t *byte_pos_ptr)
 24475 {
 24476   if (!display_line_numbers_widen || (BEGV == BEG && ZV == Z))
 24477     return display_count_lines (start_byte, limit_byte, count, byte_pos_ptr);
 24478 
 24479   ptrdiff_t val;
 24480   specpdl_ref pdl_count = SPECPDL_INDEX ();
 24481   record_unwind_protect (save_restriction_restore, save_restriction_save ());
 24482   labeled_restrictions_remove_in_current_buffer ();
 24483   Fwiden ();
 24484   val = display_count_lines (start_byte, limit_byte, count, byte_pos_ptr);
 24485   unbind_to (pdl_count, Qnil);
 24486   return val;
 24487 }
 24488 
 24489 /* Count the number of screen lines in window IT->w between character
 24490    position IT_CHARPOS(*IT) and the line showing that window's point.  */
 24491 static ptrdiff_t
 24492 display_count_lines_visually (struct it *it)
 24493 {
 24494   struct it tem_it;
 24495   ptrdiff_t to;
 24496   struct text_pos from;
 24497 
 24498   /* If we already calculated a relative line number, use that.  This
 24499      trick relies on the fact that visual lines (a.k.a. "glyph rows")
 24500      are laid out sequentially, one by one, for each sequence of calls
 24501      to display_line or other similar function that follows a call to
 24502      init_iterator.  */
 24503   if (it->lnum_bytepos > 0)
 24504     return it->lnum + 1;
 24505   else
 24506     {
 24507       specpdl_ref count = SPECPDL_INDEX ();
 24508 
 24509       if (IT_CHARPOS (*it) <= PT)
 24510         {
 24511           from = it->current.pos;
 24512           to = PT;
 24513         }
 24514       else
 24515         {
 24516           SET_TEXT_POS (from, PT, PT_BYTE);
 24517           to = IT_CHARPOS (*it);
 24518         }
 24519       /* Need to disable visual mode temporarily, since otherwise the
 24520          call to move_it_to below and inside start_display will cause
 24521          infinite recursion.  */
 24522       specbind (Qdisplay_line_numbers, Qrelative);
 24523       start_display (&tem_it, it->w, from);
 24524       /* Some redisplay optimizations could invoke us very far from
 24525          PT, which will make the caller painfully slow.  There should
 24526          be no need to go too far beyond the window's bottom, as any
 24527          such optimization will fail to show point anyway.  */
 24528       move_it_to (&tem_it, to, -1,
 24529                   tem_it.last_visible_y
 24530                   + (SCROLL_LIMIT + 10) * FRAME_LINE_HEIGHT (tem_it.f),
 24531                   -1, MOVE_TO_POS | MOVE_TO_Y);
 24532       unbind_to (count, Qnil);
 24533       return IT_CHARPOS (*it) <= PT ? -tem_it.vpos : tem_it.vpos;
 24534     }
 24535 }
 24536 
 24537 /* Produce the line-number glyphs for the current glyph_row.  If
 24538    IT->glyph_row is non-NULL, populate the row with the produced
 24539    glyphs.  */
 24540 static void
 24541 maybe_produce_line_number (struct it *it)
 24542 {
 24543   ptrdiff_t last_line = it->lnum;
 24544   ptrdiff_t start_from, bytepos;
 24545   ptrdiff_t this_line;
 24546   bool first_time = false;
 24547   ptrdiff_t beg_byte;
 24548   ptrdiff_t z_byte;
 24549   bool line_numbers_wide;
 24550   void *itdata = bidi_shelve_cache ();
 24551 
 24552   if (display_line_numbers_offset
 24553       && !display_line_numbers_widen
 24554       && !EQ (Vdisplay_line_numbers, Qvisual)
 24555       && !EQ (Vdisplay_line_numbers, Qrelative))
 24556     line_numbers_wide = true;
 24557   else
 24558     line_numbers_wide = display_line_numbers_widen;
 24559 
 24560   beg_byte = line_numbers_wide ? BEG_BYTE : BEGV_BYTE;
 24561   z_byte = line_numbers_wide ? Z_BYTE : ZV_BYTE;
 24562 
 24563   if (EQ (Vdisplay_line_numbers, Qvisual))
 24564     this_line = display_count_lines_visually (it);
 24565   else
 24566     {
 24567       if (!last_line)
 24568         {
 24569           /* If possible, reuse data cached by line-number-mode.  */
 24570           if (it->w->base_line_number > 0
 24571               && it->w->base_line_pos > 0
 24572               && it->w->base_line_pos <= IT_CHARPOS (*it)
 24573               /* line-number-mode always displays narrowed line
 24574                  numbers, so we cannot use its data if the user wants
 24575                  line numbers that disregard narrowing, or if the
 24576                  buffer's narrowing has just changed.  */
 24577               && !(line_numbers_wide
 24578                    && (BEG_BYTE != BEGV_BYTE || Z_BYTE != ZV_BYTE))
 24579               && !current_buffer->clip_changed)
 24580             {
 24581               start_from = CHAR_TO_BYTE (it->w->base_line_pos);
 24582               last_line = it->w->base_line_number - 1;
 24583             }
 24584           else
 24585             start_from = beg_byte;
 24586           if (!it->lnum_bytepos)
 24587             first_time = true;
 24588         }
 24589       else
 24590         start_from = it->lnum_bytepos;
 24591 
 24592       /* Paranoia: what if someone changes the narrowing since the
 24593          last time display_line was called?  Shouldn't really happen,
 24594          but who knows what some crazy Lisp invoked by :eval could do?  */
 24595       if (!(beg_byte <= start_from && start_from <= z_byte))
 24596         {
 24597           last_line = 0;
 24598           start_from = beg_byte;
 24599         }
 24600 
 24601       this_line =
 24602         last_line + display_count_lines_logically (start_from,
 24603                                                    IT_BYTEPOS (*it),
 24604                                                    IT_CHARPOS (*it), &bytepos);
 24605       eassert (this_line > 0 || (this_line == 0 && start_from == beg_byte));
 24606       eassert (bytepos == IT_BYTEPOS (*it));
 24607     }
 24608 
 24609   /* Record the line number information.  */
 24610   if (this_line != last_line || !it->lnum_bytepos)
 24611     {
 24612       it->lnum = this_line;
 24613       it->lnum_bytepos = IT_BYTEPOS (*it);
 24614     }
 24615 
 24616   /* Produce the glyphs for the line number.  */
 24617   struct it tem_it;
 24618   char lnum_buf[INT_STRLEN_BOUND (ptrdiff_t) + 1];
 24619   bool beyond_zv = IT_BYTEPOS (*it) >= ZV_BYTE ? true : false;
 24620   ptrdiff_t lnum_offset = -1; /* to produce 1-based line numbers */
 24621   int lnum_face_id = merge_faces (it->w, Qline_number, 0, DEFAULT_FACE_ID);
 24622   int current_lnum_face_id
 24623     = merge_faces (it->w, Qline_number_current_line, 0, DEFAULT_FACE_ID);
 24624   /* From here onwards, we must prevent freeing realized faces, because
 24625      we are using the above 2 face IDs for the glyphs we produce.  */
 24626   bool save_free_realized_faces = inhibit_free_realized_faces;
 24627   inhibit_free_realized_faces = true;
 24628   /* Compute point's line number if needed.  */
 24629   if ((EQ (Vdisplay_line_numbers, Qrelative)
 24630        || EQ (Vdisplay_line_numbers, Qvisual)
 24631        || lnum_face_id != current_lnum_face_id)
 24632       && !it->pt_lnum)
 24633     {
 24634       ptrdiff_t ignored;
 24635       if (PT_BYTE > it->lnum_bytepos && !EQ (Vdisplay_line_numbers, Qvisual))
 24636         it->pt_lnum =
 24637           this_line + display_count_lines_logically (it->lnum_bytepos, PT_BYTE,
 24638                                                      PT, &ignored);
 24639       else
 24640         it->pt_lnum = display_count_lines_logically (beg_byte, PT_BYTE, PT,
 24641                                                      &ignored);
 24642     }
 24643   /* Compute the required width if needed.  */
 24644   if (!it->lnum_width)
 24645     {
 24646       if (FIXNATP (Vdisplay_line_numbers_width))
 24647         it->lnum_width = XFIXNAT (Vdisplay_line_numbers_width);
 24648 
 24649       /* Max line number to be displayed cannot be more than the one
 24650          corresponding to the last row of the desired matrix.  */
 24651       ptrdiff_t max_lnum;
 24652 
 24653       if (NILP (Vdisplay_line_numbers_current_absolute)
 24654           && (EQ (Vdisplay_line_numbers, Qrelative)
 24655               || EQ (Vdisplay_line_numbers, Qvisual)))
 24656         /* We subtract one more because the current line is always
 24657            zero in this mode.  */
 24658         max_lnum = it->w->desired_matrix->nrows - 2;
 24659       else if (EQ (Vdisplay_line_numbers, Qvisual))
 24660         max_lnum = it->pt_lnum + it->w->desired_matrix->nrows - 1;
 24661       else
 24662         max_lnum = this_line + it->w->desired_matrix->nrows - 1 - it->vpos;
 24663       max_lnum = max (1, max_lnum);
 24664       it->lnum_width = max (it->lnum_width, log10 (max_lnum) + 1);
 24665       eassert (it->lnum_width > 0);
 24666     }
 24667   if (EQ (Vdisplay_line_numbers, Qrelative))
 24668     lnum_offset = it->pt_lnum;
 24669   else if (EQ (Vdisplay_line_numbers, Qvisual))
 24670     lnum_offset = 0;
 24671   else if (display_line_numbers_offset)
 24672     lnum_offset -= display_line_numbers_offset;
 24673 
 24674   /* Under 'relative', display the absolute line number for the
 24675      current line, unless the user requests otherwise.  */
 24676   ptrdiff_t lnum_to_display = eabs (this_line - lnum_offset);
 24677   if ((EQ (Vdisplay_line_numbers, Qrelative)
 24678        || EQ (Vdisplay_line_numbers, Qvisual))
 24679       && lnum_to_display == 0
 24680       && !NILP (Vdisplay_line_numbers_current_absolute))
 24681     lnum_to_display = it->pt_lnum + 1;
 24682   /* In L2R rows we need to append the blank separator, in R2L
 24683      rows we need to prepend it.  But this function is usually
 24684      called when no display elements were produced from the
 24685      following line, so the paragraph direction might be unknown.
 24686      Therefore we cheat and add 2 blanks, one on either side.  */
 24687   pint2str (lnum_buf, it->lnum_width + 1, lnum_to_display);
 24688   strcat (lnum_buf, " ");
 24689 
 24690   /* Setup for producing the glyphs.  */
 24691   init_iterator (&tem_it, it->w, -1, -1, &scratch_glyph_row,
 24692                  /* FIXME: Use specialized face.  */
 24693                  DEFAULT_FACE_ID);
 24694   scratch_glyph_row.reversed_p = false;
 24695   scratch_glyph_row.used[TEXT_AREA] = 0;
 24696   SET_TEXT_POS (tem_it.position, 0, 0);
 24697   tem_it.avoid_cursor_p = true;
 24698   tem_it.bidi_p = true;
 24699   tem_it.bidi_it.type = WEAK_EN;
 24700   /* According to UAX#9, EN goes up 2 levels in L2R paragraph and
 24701      1 level in R2L paragraphs.  Emulate that, assuming we are in
 24702      an L2R paragraph.  */
 24703   tem_it.bidi_it.resolved_level = 2;
 24704 
 24705   /* We must leave space for 2 glyphs for continuation and truncation,
 24706      and at least one glyph for buffer text.  */
 24707   int width_limit =
 24708     tem_it.last_visible_x - tem_it.first_visible_x
 24709     - 3 * FRAME_COLUMN_WIDTH (it->f);
 24710 
 24711   tem_it.face_id = lnum_face_id;
 24712   /* Avoid displaying any face other than line-number on
 24713      empty lines beyond EOB.  */
 24714   if (lnum_face_id != current_lnum_face_id
 24715       && (EQ (Vdisplay_line_numbers, Qvisual)
 24716           ? this_line == 0
 24717           : this_line == it->pt_lnum)
 24718       && it->what != IT_EOB)
 24719     tem_it.face_id = current_lnum_face_id;
 24720   else if (!beyond_zv)
 24721     {
 24722       if (display_line_numbers_major_tick > 0
 24723           && (lnum_to_display % display_line_numbers_major_tick == 0))
 24724         tem_it.face_id = merge_faces (it->w, Qline_number_major_tick,
 24725                                       0, DEFAULT_FACE_ID);
 24726       else if (display_line_numbers_minor_tick > 0
 24727                && (lnum_to_display % display_line_numbers_minor_tick == 0))
 24728         tem_it.face_id = merge_faces (it->w, Qline_number_minor_tick,
 24729                                       0, DEFAULT_FACE_ID);
 24730     }
 24731 
 24732   /* Produce glyphs for the line number in a scratch glyph_row.  */
 24733   for (const char *p = lnum_buf; *p; p++)
 24734     {
 24735       /* For continuation lines and lines after ZV, instead of a line
 24736          number, produce a blank prefix of the same width.  */
 24737       if (beyond_zv
 24738           /* Don't display the same line number more than once.  */
 24739           || (!EQ (Vdisplay_line_numbers, Qvisual)
 24740               && (it->continuation_lines_width > 0
 24741                   || (this_line == last_line && !first_time))))
 24742         tem_it.c = tem_it.char_to_display = ' ';
 24743       else
 24744         tem_it.c = tem_it.char_to_display = *p;
 24745       tem_it.len = 1;
 24746       /* Make sure these glyphs will have a "position" of -1.  */
 24747       SET_TEXT_POS (tem_it.position, -1, -1);
 24748       PRODUCE_GLYPHS (&tem_it);
 24749 
 24750       /* Stop producing glyphs, and refrain from producing the line
 24751          number, if we don't have enough space on this line.  */
 24752       if (tem_it.current_x >= width_limit)
 24753         {
 24754           it->lnum_width = 0;
 24755           it->lnum_pixel_width = 0;
 24756           bidi_unshelve_cache (itdata, false);
 24757           inhibit_free_realized_faces = save_free_realized_faces;
 24758           return;
 24759         }
 24760     }
 24761 
 24762   inhibit_free_realized_faces = save_free_realized_faces;
 24763 
 24764   /* Record the width in pixels we need for the line number display.  */
 24765   it->lnum_pixel_width = tem_it.current_x;
 24766   /* Copy the produced glyphs into IT's glyph_row.  */
 24767   struct glyph *g = scratch_glyph_row.glyphs[TEXT_AREA];
 24768   struct glyph *e = g + scratch_glyph_row.used[TEXT_AREA];
 24769   struct glyph *p = it->glyph_row ? it->glyph_row->glyphs[TEXT_AREA] : NULL;
 24770   short *u = it->glyph_row ? &it->glyph_row->used[TEXT_AREA] : NULL;
 24771 
 24772   eassert (it->glyph_row == NULL || it->glyph_row->used[TEXT_AREA] == 0);
 24773 
 24774   for ( ; g < e; g++)
 24775     {
 24776       it->current_x += g->pixel_width;
 24777       /* The following is important when this function is called
 24778          from move_it_in_display_line_to: HPOS is incremented only
 24779          when we are in the visible portion of the glyph row.  */
 24780       if (it->current_x > it->first_visible_x)
 24781         it->hpos++;
 24782       if (p)
 24783         {
 24784           *p++ = *g;
 24785           (*u)++;
 24786         }
 24787     }
 24788 
 24789   /* Update IT's metrics due to glyphs produced for line numbers.
 24790      Don't do that for rows beyond ZV, to avoid displaying a cursor of
 24791      different dimensions there.  */
 24792   if (!beyond_zv)
 24793     {
 24794       if (it->glyph_row)
 24795         {
 24796           struct glyph_row *row = it->glyph_row;
 24797 
 24798           it->max_ascent = max (row->ascent, tem_it.max_ascent);
 24799           it->max_descent = max (row->height - row->ascent, tem_it.max_descent);
 24800           it->max_phys_ascent = max (row->phys_ascent, tem_it.max_phys_ascent);
 24801           it->max_phys_descent = max (row->phys_height - row->phys_ascent,
 24802                                       tem_it.max_phys_descent);
 24803         }
 24804       else
 24805         {
 24806           it->max_ascent = max (it->max_ascent, tem_it.max_ascent);
 24807           it->max_descent = max (it->max_descent, tem_it.max_descent);
 24808           it->max_phys_ascent = max (it->max_phys_ascent,
 24809                                      tem_it.max_phys_ascent);
 24810           it->max_phys_descent = max (it->max_phys_descent,
 24811                                       tem_it.max_phys_descent);
 24812         }
 24813     }
 24814 
 24815   it->line_number_produced_p = true;
 24816 
 24817   bidi_unshelve_cache (itdata, false);
 24818 }
 24819 
 24820 /* Return true if this glyph row needs a line number to be produced
 24821    for it.  */
 24822 static bool
 24823 should_produce_line_number (struct it *it)
 24824 {
 24825   if (NILP (Vdisplay_line_numbers))
 24826     return false;
 24827 
 24828   /* Don't display line numbers in minibuffer windows.  */
 24829   if (MINI_WINDOW_P (it->w))
 24830     return false;
 24831 
 24832 #ifdef HAVE_WINDOW_SYSTEM
 24833   /* Don't display line number in tooltip frames.  */
 24834   if (FRAME_TOOLTIP_P (XFRAME (WINDOW_FRAME (it->w))))
 24835     return false;
 24836 #endif
 24837 
 24838   /* If the character at current position has a non-nil special
 24839      property, disable line numbers for this row.  This is for
 24840      packages such as company-mode, which need this for their tricky
 24841      layout, where line numbers get in the way.  */
 24842   Lisp_Object val = Fget_char_property (make_fixnum (IT_CHARPOS (*it)),
 24843                                         Qdisplay_line_numbers_disable,
 24844                                         it->window);
 24845   /* For ZV, we need to also look in empty overlays at that point,
 24846      because get-char-property always returns nil for ZV, except if
 24847      the property is in 'default-text-properties'.  */
 24848   if (NILP (val) && IT_CHARPOS (*it) >= ZV)
 24849     val = disable_line_numbers_overlay_at_eob ();
 24850   return NILP (val) ? true : false;
 24851 }
 24852 
 24853 /* Return true if ROW has no glyphs except those inserted by the
 24854    display engine.  This is needed for indicate-empty-lines and
 24855    similar features when the glyph row starts with glyphs which didn't
 24856    come from buffer or string.  */
 24857 static bool
 24858 row_text_area_empty (struct glyph_row *row)
 24859 {
 24860   if (!row->reversed_p)
 24861     {
 24862       for (struct glyph *g = row->glyphs[TEXT_AREA];
 24863            g < row->glyphs[TEXT_AREA] + row->used[TEXT_AREA];
 24864            g++)
 24865         if (!NILP (g->object) || g->charpos > 0)
 24866           return false;
 24867     }
 24868   else
 24869     {
 24870       for (struct glyph *g = row->glyphs[TEXT_AREA] + row->used[TEXT_AREA] - 1;
 24871            g > row->glyphs[TEXT_AREA];
 24872            g--)
 24873         if (!NILP ((g - 1)->object) || (g - 1)->charpos > 0)
 24874           return false;
 24875     }
 24876 
 24877   return true;
 24878 }
 24879 
 24880 /* Construct the glyph row IT->glyph_row in the desired matrix of
 24881    IT->w from text at the current position of IT.  See dispextern.h
 24882    for an overview of struct it.  Value is true if
 24883    IT->glyph_row displays text, as opposed to a line displaying ZV
 24884    only.  CURSOR_VPOS is the window-relative vertical position of
 24885    the glyph row displaying the cursor, or -1 if unknown.  */
 24886 
 24887 static bool
 24888 display_line (struct it *it, int cursor_vpos)
 24889 {
 24890   struct glyph_row *row = it->glyph_row;
 24891   Lisp_Object overlay_arrow_string;
 24892   struct it wrap_it;
 24893   void *wrap_data = NULL;
 24894   bool may_wrap = false;
 24895   int wrap_x UNINIT;
 24896   int wrap_row_used = -1;
 24897   int wrap_row_ascent UNINIT, wrap_row_height UNINIT;
 24898   int wrap_row_phys_ascent UNINIT, wrap_row_phys_height UNINIT;
 24899   int wrap_row_extra_line_spacing UNINIT;
 24900   ptrdiff_t wrap_row_min_pos UNINIT, wrap_row_min_bpos UNINIT;
 24901   ptrdiff_t wrap_row_max_pos UNINIT, wrap_row_max_bpos UNINIT;
 24902   int cvpos;
 24903   ptrdiff_t min_pos = ZV + 1, max_pos = 0;
 24904   ptrdiff_t min_bpos UNINIT, max_bpos UNINIT;
 24905   bool pending_handle_line_prefix = false;
 24906   int tab_line = window_wants_tab_line (it->w);
 24907   int header_line = window_wants_header_line (it->w);
 24908   bool hscroll_this_line = (cursor_vpos >= 0
 24909                             && it->vpos == cursor_vpos - tab_line - header_line
 24910                             && hscrolling_current_line_p (it->w));
 24911   int first_visible_x = it->first_visible_x;
 24912   int last_visible_x = it->last_visible_x;
 24913   int x_incr = 0;
 24914 
 24915   /* We always start displaying at hpos zero even if hscrolled.  */
 24916   eassert (it->hpos == 0 && it->current_x == 0);
 24917 
 24918   if (MATRIX_ROW_VPOS (row, it->w->desired_matrix)
 24919       >= it->w->desired_matrix->nrows)
 24920     {
 24921       it->w->nrows_scale_factor++;
 24922       it->f->fonts_changed = true;
 24923       return false;
 24924     }
 24925 
 24926   /* Clear the result glyph row and enable it.  */
 24927   prepare_desired_row (it->w, row, false);
 24928 
 24929   row->y = it->current_y;
 24930   row->start = it->start;
 24931   row->continuation_lines_width = it->continuation_lines_width;
 24932   row->displays_text_p = true;
 24933   row->starts_in_middle_of_char_p = it->starts_in_middle_of_char_p;
 24934   it->starts_in_middle_of_char_p = false;
 24935   it->stretch_adjust = 0;
 24936   it->line_number_produced_p = false;
 24937 
 24938   /* If we are going to display the cursor's line, account for the
 24939      hscroll of that line.  We subtract the window's min_hscroll,
 24940      because that was already accounted for in init_iterator.  */
 24941   if (hscroll_this_line)
 24942     x_incr =
 24943       (window_hscroll_limited (it->w, it->f) - it->w->min_hscroll)
 24944       * FRAME_COLUMN_WIDTH (it->f);
 24945 
 24946   bool line_number_needed = should_produce_line_number (it);
 24947 
 24948   /* Move over display elements that are not visible because we are
 24949      hscrolled.  This may stop at an x-position < first_visible_x
 24950      if the first glyph is partially visible or if we hit a line end.  */
 24951   if (it->current_x < it->first_visible_x + x_incr)
 24952     {
 24953       enum move_it_result move_result;
 24954 
 24955       this_line_min_pos = row->start.pos;
 24956       if (hscroll_this_line)
 24957         {
 24958           it->first_visible_x += x_incr;
 24959           it->last_visible_x  += x_incr;
 24960         }
 24961       if (current_buffer->long_line_optimizations_p
 24962           && it->line_wrap == TRUNCATE
 24963           && window_hscroll_limited (it->w, it->f) > large_hscroll_threshold)
 24964         {
 24965           /* Special optimization for very long and truncated lines
 24966              which are hscrolled far to the left: jump directly to the
 24967              (approximate) position that is visible, instead of slowly
 24968              walking there.  */
 24969           ptrdiff_t chars_to_skip =
 24970             it->first_visible_x / FRAME_COLUMN_WIDTH (it->f);
 24971           move_result = fast_move_it_horizontally (it, chars_to_skip);
 24972 
 24973           if (move_result == MOVE_X_REACHED)
 24974             it->current_x = it->first_visible_x;
 24975           else  /* use arbitrary value < first_visible_x */
 24976             it->current_x = it->first_visible_x - FRAME_COLUMN_WIDTH (it->f);
 24977         }
 24978       else
 24979         move_result = move_it_in_display_line_to (it, ZV, it->first_visible_x,
 24980                                                   MOVE_TO_POS | MOVE_TO_X);
 24981       /* If we are under a large hscroll, move_it_in_display_line_to
 24982          could hit the end of the line without reaching
 24983          first_visible_x.  Pretend that we did reach it.  This is
 24984          especially important on a TTY, where we will call
 24985          extend_face_to_end_of_line, which needs to know how many
 24986          blank glyphs to produce.  */
 24987       if (it->current_x < it->first_visible_x
 24988           && (move_result == MOVE_NEWLINE_OR_CR
 24989               || move_result == MOVE_POS_MATCH_OR_ZV))
 24990         it->current_x = it->first_visible_x;
 24991 
 24992       /* In case move_it_in_display_line_to above "produced" the line
 24993          number.  */
 24994       it->line_number_produced_p = false;
 24995 
 24996       /* Record the smallest positions seen while we moved over
 24997          display elements that are not visible.  This is needed by
 24998          redisplay_internal for optimizing the case where the cursor
 24999          stays inside the same line.  The rest of this function only
 25000          considers positions that are actually displayed, so
 25001          RECORD_MAX_MIN_POS will not otherwise record positions that
 25002          are hscrolled to the left of the left edge of the window.  */
 25003       min_pos = CHARPOS (this_line_min_pos);
 25004       min_bpos = BYTEPOS (this_line_min_pos);
 25005 
 25006       /* Produce line number, if needed.  */
 25007       if (line_number_needed)
 25008         maybe_produce_line_number (it);
 25009     }
 25010   else if (it->area == TEXT_AREA)
 25011     {
 25012       /* Line numbers should precede the line-prefix or wrap-prefix.  */
 25013       if (line_number_needed)
 25014         maybe_produce_line_number (it);
 25015 
 25016       /* We only do this when not calling move_it_in_display_line_to
 25017          above, because that function calls itself handle_line_prefix.  */
 25018       handle_line_prefix (it);
 25019     }
 25020   else
 25021     {
 25022       /* Line-prefix and wrap-prefix are always displayed in the text
 25023          area.  But if this is the first call to display_line after
 25024          init_iterator, the iterator might have been set up to write
 25025          into a marginal area, e.g. if the line begins with some
 25026          display property that writes to the margins.  So we need to
 25027          wait with the call to handle_line_prefix until whatever
 25028          writes to the margin has done its job.  */
 25029       pending_handle_line_prefix = true;
 25030     }
 25031 
 25032   /* Get the initial row height.  This is either the height of the
 25033      text hscrolled, if there is any, or zero.  */
 25034   row->ascent = it->max_ascent;
 25035   row->height = it->max_ascent + it->max_descent;
 25036   row->phys_ascent = it->max_phys_ascent;
 25037   row->phys_height = it->max_phys_ascent + it->max_phys_descent;
 25038   row->extra_line_spacing = it->max_extra_line_spacing;
 25039 
 25040 /* Utility macro to record max and min buffer positions seen until now.  */
 25041 #define RECORD_MAX_MIN_POS(IT)                                  \
 25042   do                                                            \
 25043     {                                                           \
 25044       bool composition_p                                        \
 25045         = !STRINGP ((IT)->string) && ((IT)->what == IT_COMPOSITION); \
 25046       ptrdiff_t current_pos =                                   \
 25047         composition_p ? (IT)->cmp_it.charpos                    \
 25048                       : IT_CHARPOS (*(IT));                     \
 25049       ptrdiff_t current_bpos =                                  \
 25050         composition_p ? CHAR_TO_BYTE (current_pos)              \
 25051                       : IT_BYTEPOS (*(IT));                     \
 25052       if (current_pos < min_pos)                                \
 25053         {                                                       \
 25054           min_pos = current_pos;                                \
 25055           min_bpos = current_bpos;                              \
 25056         }                                                       \
 25057       if (IT_CHARPOS (*it) > max_pos)                           \
 25058         {                                                       \
 25059           max_pos = IT_CHARPOS (*it);                           \
 25060           max_bpos = IT_BYTEPOS (*it);                          \
 25061         }                                                       \
 25062     }                                                           \
 25063   while (false)
 25064 
 25065   /* Loop generating characters.  The loop is left with IT on the next
 25066      character to display.  */
 25067   while (true)
 25068     {
 25069       int n_glyphs_before, hpos_before, x_before;
 25070       int x, nglyphs;
 25071       int ascent = 0, descent = 0, phys_ascent = 0, phys_descent = 0;
 25072 
 25073       /* Retrieve the next thing to display.  Value is false if end of
 25074          buffer reached.  */
 25075       if (!get_next_display_element (it))
 25076         {
 25077           bool row_has_glyphs = false;
 25078           /* Maybe add a space at the end of this line that is used to
 25079              display the cursor there under X.  Set the charpos of the
 25080              first glyph of blank lines not corresponding to any text
 25081              to -1.  */
 25082           if (IT_OVERFLOW_NEWLINE_INTO_FRINGE (it))
 25083             row->exact_window_width_line_p = true;
 25084           else if ((append_space_for_newline (it, true)
 25085                     && row->used[TEXT_AREA] == 1)
 25086                    || row->used[TEXT_AREA] == 0
 25087                    || (row_has_glyphs = row_text_area_empty (row)))
 25088             {
 25089               row->glyphs[TEXT_AREA]->charpos = -1;
 25090               /* Don't reset the displays_text_p flag if we are
 25091                  displaying line numbers or line-prefix.  */
 25092               if (!row_has_glyphs)
 25093                 row->displays_text_p = false;
 25094 
 25095               if (!NILP (BVAR (XBUFFER (it->w->contents), indicate_empty_lines))
 25096                   && (!MINI_WINDOW_P (it->w)))
 25097                 row->indicate_empty_line_p = true;
 25098             }
 25099 
 25100           it->continuation_lines_width = 0;
 25101           /* Reset those iterator values set from display property
 25102              values.  This is for the case when the display property
 25103              ends at ZV, and is not a replacing property, so pop_it is
 25104              not called.  */
 25105           it->font_height = Qnil;
 25106           it->voffset = 0;
 25107           row->ends_at_zv_p = true;
 25108           /* A row that displays right-to-left text must always have
 25109              its last face extended all the way to the end of line,
 25110              even if this row ends in ZV, because we still write to
 25111              the screen left to right.  We also need to extend the
 25112              last face if the default face is remapped to some
 25113              different face, otherwise the functions that clear
 25114              portions of the screen will clear with the default face's
 25115              background color.  */
 25116           if (row->reversed_p
 25117               || lookup_basic_face (it->w, it->f, DEFAULT_FACE_ID)
 25118               != DEFAULT_FACE_ID)
 25119             extend_face_to_end_of_line (it);
 25120           break;
 25121         }
 25122 
 25123       /* Now, get the metrics of what we want to display.  This also
 25124          generates glyphs in `row' (which is IT->glyph_row).  */
 25125       n_glyphs_before = row->used[TEXT_AREA];
 25126       x = it->current_x;
 25127 
 25128       /* Remember the line height so far in case the next element doesn't
 25129          fit on the line.  */
 25130       if (it->line_wrap != TRUNCATE)
 25131         {
 25132           ascent = it->max_ascent;
 25133           descent = it->max_descent;
 25134           phys_ascent = it->max_phys_ascent;
 25135           phys_descent = it->max_phys_descent;
 25136 
 25137           if (it->line_wrap == WORD_WRAP && it->area == TEXT_AREA)
 25138             {
 25139               bool next_may_wrap = may_wrap;
 25140               /* Can we wrap after this character?  */
 25141               if (char_can_wrap_after (it))
 25142                 next_may_wrap = true;
 25143               else
 25144                 next_may_wrap = false;
 25145               /* Can we wrap here? */
 25146               if (may_wrap && char_can_wrap_before (it))
 25147                 {
 25148                   SAVE_IT (wrap_it, *it, wrap_data);
 25149                   wrap_x = x;
 25150                   wrap_row_used = row->used[TEXT_AREA];
 25151                   wrap_row_ascent = row->ascent;
 25152                   wrap_row_height = row->height;
 25153                   wrap_row_phys_ascent = row->phys_ascent;
 25154                   wrap_row_phys_height = row->phys_height;
 25155                   wrap_row_extra_line_spacing = row->extra_line_spacing;
 25156                   wrap_row_min_pos = min_pos;
 25157                   wrap_row_min_bpos = min_bpos;
 25158                   wrap_row_max_pos = max_pos;
 25159                   wrap_row_max_bpos = max_bpos;
 25160                 }
 25161               /* Update may_wrap for the next iteration.  */
 25162               may_wrap = next_may_wrap;
 25163             }
 25164         }
 25165 
 25166       PRODUCE_GLYPHS (it);
 25167 
 25168       /* If this display element was in marginal areas, continue with
 25169          the next one.  */
 25170       if (it->area != TEXT_AREA)
 25171         {
 25172           row->ascent = max (row->ascent, it->max_ascent);
 25173           row->height = max (row->height, it->max_ascent + it->max_descent);
 25174           row->phys_ascent = max (row->phys_ascent, it->max_phys_ascent);
 25175           row->phys_height = max (row->phys_height,
 25176                                   it->max_phys_ascent + it->max_phys_descent);
 25177           row->extra_line_spacing = max (row->extra_line_spacing,
 25178                                          it->max_extra_line_spacing);
 25179           set_iterator_to_next (it, true);
 25180           /* If we didn't handle the line/wrap prefix above, and the
 25181              call to set_iterator_to_next just switched to TEXT_AREA,
 25182              process the prefix now.  */
 25183           if (it->area == TEXT_AREA && pending_handle_line_prefix)
 25184             {
 25185               /* Line numbers should precede the line-prefix or wrap-prefix.  */
 25186               if (line_number_needed)
 25187                 maybe_produce_line_number (it);
 25188 
 25189               pending_handle_line_prefix = false;
 25190               handle_line_prefix (it);
 25191             }
 25192           continue;
 25193         }
 25194 
 25195       /* Does the display element fit on the line?  If we truncate
 25196          lines, we should draw past the right edge of the window.  If
 25197          we don't truncate, we want to stop so that we can display the
 25198          continuation glyph before the right margin.  If lines are
 25199          continued, there are two possible strategies for characters
 25200          resulting in more than 1 glyph (e.g. tabs): Display as many
 25201          glyphs as possible in this line and leave the rest for the
 25202          continuation line, or display the whole element in the next
 25203          line.  Original redisplay did the former, so we do it also.  */
 25204       nglyphs = row->used[TEXT_AREA] - n_glyphs_before;
 25205       hpos_before = it->hpos;
 25206       x_before = x;
 25207 
 25208       if (/* Not a newline.  */
 25209           nglyphs > 0
 25210           /* Glyphs produced fit entirely in the line.  */
 25211           && it->current_x < it->last_visible_x)
 25212         {
 25213           it->hpos += nglyphs;
 25214           row->ascent = max (row->ascent, it->max_ascent);
 25215           row->height = max (row->height, it->max_ascent + it->max_descent);
 25216           row->phys_ascent = max (row->phys_ascent, it->max_phys_ascent);
 25217           row->phys_height = max (row->phys_height,
 25218                                   it->max_phys_ascent + it->max_phys_descent);
 25219           row->extra_line_spacing = max (row->extra_line_spacing,
 25220                                          it->max_extra_line_spacing);
 25221           if (it->current_x - it->pixel_width < it->first_visible_x
 25222               /* When line numbers are displayed, row->x should not be
 25223                  offset, as the first glyph after the line number can
 25224                  never be partially visible.  */
 25225               && !line_number_needed
 25226               /* In R2L rows, we arrange in extend_face_to_end_of_line
 25227                  to add a right offset to the line, by a suitable
 25228                  change to the stretch glyph that is the leftmost
 25229                  glyph of the line.  */
 25230               && !row->reversed_p)
 25231             row->x = x - it->first_visible_x;
 25232           /* Record the maximum and minimum buffer positions seen so
 25233              far in glyphs that will be displayed by this row.  */
 25234           if (it->bidi_p)
 25235             RECORD_MAX_MIN_POS (it);
 25236         }
 25237       else
 25238         {
 25239           int i, new_x;
 25240           struct glyph *glyph;
 25241 
 25242           for (i = 0; i < nglyphs; ++i, x = new_x)
 25243             {
 25244               /* Identify the glyphs added by the last call to
 25245                  PRODUCE_GLYPHS.  In R2L rows, they are prepended to
 25246                  the previous glyphs.  */
 25247               if (!row->reversed_p)
 25248                 glyph = row->glyphs[TEXT_AREA] + n_glyphs_before + i;
 25249               else
 25250                 glyph = row->glyphs[TEXT_AREA] + nglyphs - 1 - i;
 25251               new_x = x + glyph->pixel_width;
 25252 
 25253               if (/* Lines are continued.  */
 25254                   it->line_wrap != TRUNCATE
 25255                   && (/* Glyph doesn't fit on the line.  */
 25256                       new_x > it->last_visible_x
 25257                       /* Or it fits exactly on a window system frame.  */
 25258                       || (new_x == it->last_visible_x
 25259                           && FRAME_WINDOW_P (it->f)
 25260                           && (row->reversed_p
 25261                               ? WINDOW_LEFT_FRINGE_WIDTH (it->w)
 25262                               : WINDOW_RIGHT_FRINGE_WIDTH (it->w)))))
 25263                 {
 25264                   /* End of a continued line.  */
 25265 
 25266                   if (it->hpos == 0
 25267                       || (new_x == it->last_visible_x
 25268                           && FRAME_WINDOW_P (it->f)
 25269                           && (row->reversed_p
 25270                               ? WINDOW_LEFT_FRINGE_WIDTH (it->w)
 25271                               : WINDOW_RIGHT_FRINGE_WIDTH (it->w))))
 25272                     {
 25273                       /* Current glyph is the only one on the line or
 25274                          fits exactly on the line.  We must continue
 25275                          the line because we can't draw the cursor
 25276                          after the glyph.  */
 25277                       row->continued_p = true;
 25278                       it->current_x = new_x;
 25279                       it->continuation_lines_width += new_x;
 25280                       ++it->hpos;
 25281                       if (i == nglyphs - 1)
 25282                         {
 25283                           /* If line-wrap is on, check if a previous
 25284                              wrap point was found.  */
 25285                           if (!IT_OVERFLOW_NEWLINE_INTO_FRINGE (it)
 25286                               && wrap_row_used > 0 /* Found.  */
 25287                               /* Even if there is a previous wrap
 25288                                  point, continue the line here as
 25289                                  usual, if (i) the previous character
 25290                                  allows wrapping after it, AND (ii)
 25291                                  the current character allows wrapping
 25292                                  before it.  Because this is a valid
 25293                                  break point, we can just continue to
 25294                                  the next line at here, there is no
 25295                                  need to wrap early at the previous
 25296                                  wrap point.  */
 25297                               && (!may_wrap || !char_can_wrap_before (it)))
 25298                             goto back_to_wrap;
 25299 
 25300                           /* Record the maximum and minimum buffer
 25301                              positions seen so far in glyphs that will be
 25302                              displayed by this row.  */
 25303                           if (it->bidi_p)
 25304                             RECORD_MAX_MIN_POS (it);
 25305                           set_iterator_to_next (it, true);
 25306                           if (IT_OVERFLOW_NEWLINE_INTO_FRINGE (it))
 25307                             {
 25308                               if (!get_next_display_element (it))
 25309                                 {
 25310                                   row->exact_window_width_line_p = true;
 25311                                   it->continuation_lines_width = 0;
 25312                                   it->font_height = Qnil;
 25313                                   it->voffset = 0;
 25314                                   row->continued_p = false;
 25315                                   row->ends_at_zv_p = true;
 25316                                 }
 25317                               else if (ITERATOR_AT_END_OF_LINE_P (it))
 25318                                 {
 25319                                   row->continued_p = false;
 25320                                   row->exact_window_width_line_p = true;
 25321                                 }
 25322                               /* If line-wrap is on, check if a
 25323                                  previous wrap point was found.  */
 25324                               else if (wrap_row_used > 0
 25325                                        /* Even if there is a previous
 25326                                           wrap point, continue the
 25327                                           line here as usual, if (i)
 25328                                           the previous character was a
 25329                                           space or tab AND (ii) the
 25330                                           current character is not,
 25331                                           AND (iii) the current
 25332                                           character allows wrapping
 25333                                           before it.  */
 25334                                        && (!may_wrap || !char_can_wrap_before (it)))
 25335                                 goto back_to_wrap;
 25336 
 25337                             }
 25338                         }
 25339                       else if (it->bidi_p)
 25340                         RECORD_MAX_MIN_POS (it);
 25341                       if (WINDOW_LEFT_MARGIN_WIDTH (it->w) > 0
 25342                           || WINDOW_RIGHT_MARGIN_WIDTH (it->w) > 0)
 25343                         extend_face_to_end_of_line (it);
 25344                     }
 25345                   else if (CHAR_GLYPH_PADDING_P (*glyph)
 25346                            && !FRAME_WINDOW_P (it->f))
 25347                     {
 25348                       /* A padding glyph that doesn't fit on this line.
 25349                          This means the whole character doesn't fit
 25350                          on the line.  */
 25351                       if (row->reversed_p)
 25352                         unproduce_glyphs (it, row->used[TEXT_AREA]
 25353                                                - n_glyphs_before);
 25354                       row->used[TEXT_AREA] = n_glyphs_before;
 25355 
 25356                       /* Fill the rest of the row with continuation
 25357                          glyphs like in 20.x.  */
 25358                       while (row->glyphs[TEXT_AREA] + row->used[TEXT_AREA]
 25359                              < row->glyphs[1 + TEXT_AREA])
 25360                         produce_special_glyphs (it, IT_CONTINUATION);
 25361 
 25362                       row->continued_p = true;
 25363                       it->current_x = x_before;
 25364                       it->continuation_lines_width += x_before;
 25365 
 25366                       /* Restore the height to what it was before the
 25367                          element not fitting on the line.  */
 25368                       it->max_ascent = ascent;
 25369                       it->max_descent = descent;
 25370                       it->max_phys_ascent = phys_ascent;
 25371                       it->max_phys_descent = phys_descent;
 25372                       if (WINDOW_LEFT_MARGIN_WIDTH (it->w) > 0
 25373                           || WINDOW_RIGHT_MARGIN_WIDTH (it->w) > 0)
 25374                         extend_face_to_end_of_line (it);
 25375                     }
 25376                   else if (wrap_row_used > 0)
 25377                     {
 25378                     back_to_wrap:
 25379                       if (row->reversed_p)
 25380                         unproduce_glyphs (it,
 25381                                           row->used[TEXT_AREA] - wrap_row_used);
 25382                       RESTORE_IT (it, &wrap_it, wrap_data);
 25383                       it->continuation_lines_width += wrap_x;
 25384                       row->used[TEXT_AREA] = wrap_row_used;
 25385                       row->ascent = wrap_row_ascent;
 25386                       row->height = wrap_row_height;
 25387                       row->phys_ascent = wrap_row_phys_ascent;
 25388                       row->phys_height = wrap_row_phys_height;
 25389                       row->extra_line_spacing = wrap_row_extra_line_spacing;
 25390                       min_pos = wrap_row_min_pos;
 25391                       min_bpos = wrap_row_min_bpos;
 25392                       max_pos = wrap_row_max_pos;
 25393                       max_bpos = wrap_row_max_bpos;
 25394                       row->continued_p = true;
 25395                       row->ends_at_zv_p = false;
 25396                       row->exact_window_width_line_p = false;
 25397 
 25398                       /* Make sure that a non-default face is extended
 25399                          up to the right margin of the window.  */
 25400                       extend_face_to_end_of_line (it);
 25401                     }
 25402                   else if ((it->what == IT_CHARACTER
 25403                             || it->what == IT_STRETCH
 25404                             || it->what == IT_COMPOSITION)
 25405                            && it->c == '\t' && FRAME_WINDOW_P (it->f))
 25406                     {
 25407                       /* A TAB that extends past the right edge of the
 25408                          window.  This produces a single glyph on
 25409                          window system frames.  We leave the glyph in
 25410                          this row and let it fill the row, but don't
 25411                          consume the TAB.  */
 25412                       if ((row->reversed_p
 25413                            ? WINDOW_LEFT_FRINGE_WIDTH (it->w)
 25414                            : WINDOW_RIGHT_FRINGE_WIDTH (it->w)) == 0)
 25415                         produce_special_glyphs (it, IT_CONTINUATION);
 25416                       it->continuation_lines_width += it->last_visible_x;
 25417                       row->ends_in_middle_of_char_p = true;
 25418                       row->continued_p = true;
 25419                       glyph->pixel_width = it->last_visible_x - x;
 25420                       it->starts_in_middle_of_char_p = true;
 25421                       if (WINDOW_LEFT_MARGIN_WIDTH (it->w) > 0
 25422                           || WINDOW_RIGHT_MARGIN_WIDTH (it->w) > 0)
 25423                         extend_face_to_end_of_line (it);
 25424                     }
 25425                   else
 25426                     {
 25427                       /* Something other than a TAB that draws past
 25428                          the right edge of the window.  Restore
 25429                          positions to values before the element.  */
 25430                       if (row->reversed_p)
 25431                         unproduce_glyphs (it, row->used[TEXT_AREA]
 25432                                                - (n_glyphs_before + i));
 25433                       row->used[TEXT_AREA] = n_glyphs_before + i;
 25434 
 25435                       /* Display continuation glyphs.  */
 25436                       it->current_x = x_before;
 25437                       it->continuation_lines_width += x;
 25438                       if (!FRAME_WINDOW_P (it->f)
 25439                           || (row->reversed_p
 25440                               ? WINDOW_LEFT_FRINGE_WIDTH (it->w)
 25441                               : WINDOW_RIGHT_FRINGE_WIDTH (it->w)) == 0)
 25442                         produce_special_glyphs (it, IT_CONTINUATION);
 25443                       row->continued_p = true;
 25444 
 25445                       extend_face_to_end_of_line (it);
 25446 
 25447                       if (nglyphs > 1 && i > 0)
 25448                         {
 25449                           row->ends_in_middle_of_char_p = true;
 25450                           it->starts_in_middle_of_char_p = true;
 25451                         }
 25452 
 25453                       /* Restore the height to what it was before the
 25454                          element not fitting on the line.  */
 25455                       it->max_ascent = ascent;
 25456                       it->max_descent = descent;
 25457                       it->max_phys_ascent = phys_ascent;
 25458                       it->max_phys_descent = phys_descent;
 25459                     }
 25460 
 25461                   break;
 25462                 }
 25463               else if (new_x > it->first_visible_x)
 25464                 {
 25465                   /* Increment number of glyphs actually displayed.  */
 25466                   ++it->hpos;
 25467 
 25468                   /* Record the maximum and minimum buffer positions
 25469                      seen so far in glyphs that will be displayed by
 25470                      this row.  */
 25471                   if (it->bidi_p)
 25472                     RECORD_MAX_MIN_POS (it);
 25473 
 25474                   if (x < it->first_visible_x && !row->reversed_p
 25475                       && !line_number_needed)
 25476                     /* Glyph is partially visible, i.e. row starts at
 25477                        negative X position.  Don't do that in R2L
 25478                        rows, where we arrange to add a right offset to
 25479                        the line in extend_face_to_end_of_line, by a
 25480                        suitable change to the stretch glyph that is
 25481                        the leftmost glyph of the line.  */
 25482                     row->x = x - it->first_visible_x;
 25483                   /* When the last glyph of an R2L row only fits
 25484                      partially on the line, we need to set row->x to a
 25485                      negative offset, so that the leftmost glyph is
 25486                      the one that is partially visible.  But if we are
 25487                      going to produce the truncation glyph, this will
 25488                      be taken care of in produce_special_glyphs.  */
 25489                   if (row->reversed_p
 25490                       && new_x > it->last_visible_x
 25491                       && !line_number_needed
 25492                       && !(it->line_wrap == TRUNCATE
 25493                            && WINDOW_LEFT_FRINGE_WIDTH (it->w) == 0))
 25494                     {
 25495                       eassert (FRAME_WINDOW_P (it->f));
 25496                       row->x = it->last_visible_x - new_x;
 25497                     }
 25498                 }
 25499               else
 25500                 {
 25501                   /* Glyph is completely off the left margin of the
 25502                      window.  This should not happen because of the
 25503                      move_it_in_display_line at the start of this
 25504                      function, unless the text display area of the
 25505                      window is empty.  */
 25506                   eassert (it->first_visible_x <= it->last_visible_x);
 25507                 }
 25508             }
 25509           /* Even if this display element produced no glyphs at all,
 25510              we want to record its position.  */
 25511           if (it->bidi_p && nglyphs == 0)
 25512             RECORD_MAX_MIN_POS (it);
 25513 
 25514           row->ascent = max (row->ascent, it->max_ascent);
 25515           row->height = max (row->height, it->max_ascent + it->max_descent);
 25516           row->phys_ascent = max (row->phys_ascent, it->max_phys_ascent);
 25517           row->phys_height = max (row->phys_height,
 25518                                   it->max_phys_ascent + it->max_phys_descent);
 25519           row->extra_line_spacing = max (row->extra_line_spacing,
 25520                                          it->max_extra_line_spacing);
 25521 
 25522           /* End of this display line if row is continued.  */
 25523           if (row->continued_p || row->ends_at_zv_p)
 25524             break;
 25525         }
 25526 
 25527     at_end_of_line:
 25528       /* Is this a line end?  If yes, we're also done, after making
 25529          sure that a non-default face is extended up to the right
 25530          margin of the window.  */
 25531       if (ITERATOR_AT_END_OF_LINE_P (it))
 25532         {
 25533           int used_before = row->used[TEXT_AREA];
 25534 
 25535           row->ends_in_newline_from_string_p = STRINGP (it->object);
 25536 
 25537           /* Add a space at the end of the line that is used to
 25538              display the cursor there.  */
 25539           if (!IT_OVERFLOW_NEWLINE_INTO_FRINGE (it))
 25540             append_space_for_newline (it, false);
 25541 
 25542           /* Extend the face to the end of the line.  */
 25543           extend_face_to_end_of_line (it);
 25544 
 25545           /* Make sure we have the position.  */
 25546           if (used_before == 0)
 25547             row->glyphs[TEXT_AREA]->charpos = CHARPOS (it->position);
 25548 
 25549           /* Record the position of the newline, for use in
 25550              find_row_edges.  */
 25551           it->eol_pos = it->current.pos;
 25552 
 25553           /* Consume the line end.  This skips over invisible lines.  */
 25554           set_iterator_to_next (it, true);
 25555           it->continuation_lines_width = 0;
 25556           break;
 25557         }
 25558 
 25559       /* Detect overly-wide wrap-prefixes made of (space ...) display
 25560          properties.  When such a wrap prefix reaches past the right
 25561          margin of the window, we need to avoid the call to
 25562          set_iterator_to_next below, so that it->line_wrap is left at
 25563          its TRUNCATE value wisely set by handle_line_prefix.
 25564          Otherwise, set_iterator_to_next will pop the iterator stack,
 25565          restore it->line_wrap, and redisplay might infloop.  */
 25566       bool overwide_wrap_prefix =
 25567         CONSP (it->object) && EQ (XCAR (it->object), Qspace)
 25568         && it->sp > 0 && it->method == GET_FROM_STRETCH
 25569         && it->current_x >= it->last_visible_x
 25570         && it->continuation_lines_width > 0
 25571         && it->line_wrap == TRUNCATE && it->stack[0].line_wrap != TRUNCATE;
 25572 
 25573       /* Proceed with next display element.  Note that this skips
 25574          over lines invisible because of selective display.  */
 25575       if (!overwide_wrap_prefix)
 25576         set_iterator_to_next (it, true);
 25577 
 25578       /* If we truncate lines, we are done when the last displayed
 25579          glyphs reach past the right margin of the window.  */
 25580       if (it->line_wrap == TRUNCATE
 25581           && ((FRAME_WINDOW_P (it->f)
 25582                /* Images are preprocessed in produce_image_glyph such
 25583                   that they are cropped at the right edge of the
 25584                   window, so an image glyph will always end exactly at
 25585                   last_visible_x, even if there's no right fringe.  */
 25586                && ((row->reversed_p
 25587                     ? WINDOW_LEFT_FRINGE_WIDTH (it->w)
 25588                     : WINDOW_RIGHT_FRINGE_WIDTH (it->w))
 25589                    || it->what == IT_IMAGE))
 25590               ? (it->current_x >= it->last_visible_x)
 25591               : (it->current_x > it->last_visible_x)))
 25592         {
 25593           /* Maybe add truncation glyphs.  */
 25594           if (!FRAME_WINDOW_P (it->f)
 25595               || (row->reversed_p
 25596                   ? WINDOW_LEFT_FRINGE_WIDTH (it->w)
 25597                   : WINDOW_RIGHT_FRINGE_WIDTH (it->w)) == 0)
 25598             {
 25599               int i, n;
 25600 
 25601               if (!row->reversed_p)
 25602                 {
 25603                   for (i = row->used[TEXT_AREA] - 1; i > 0; --i)
 25604                     if (!CHAR_GLYPH_PADDING_P (row->glyphs[TEXT_AREA][i]))
 25605                       break;
 25606                 }
 25607               else
 25608                 {
 25609                   for (i = 0; i < row->used[TEXT_AREA]; i++)
 25610                     if (!CHAR_GLYPH_PADDING_P (row->glyphs[TEXT_AREA][i]))
 25611                       break;
 25612                   /* Remove any padding glyphs at the front of ROW, to
 25613                      make room for the truncation glyphs we will be
 25614                      adding below.  The loop below always inserts at
 25615                      least one truncation glyph, so also remove the
 25616                      last glyph added to ROW.  */
 25617                   unproduce_glyphs (it, i + 1);
 25618                   /* Adjust i for the loop below.  */
 25619                   i = row->used[TEXT_AREA] - (i + 1);
 25620                 }
 25621 
 25622               /* produce_special_glyphs overwrites the last glyph, so
 25623                  we don't want that if we want to keep that last
 25624                  glyph, which means it's an image.  */
 25625               if (it->current_x > it->last_visible_x)
 25626                 {
 25627                   it->current_x = x_before;
 25628                   if (!FRAME_WINDOW_P (it->f))
 25629                     {
 25630                       for (n = row->used[TEXT_AREA]; i < n; ++i)
 25631                         {
 25632                           row->used[TEXT_AREA] = i;
 25633                           produce_special_glyphs (it, IT_TRUNCATION);
 25634                         }
 25635                     }
 25636                   else
 25637                     {
 25638                       row->used[TEXT_AREA] = i;
 25639                       produce_special_glyphs (it, IT_TRUNCATION);
 25640                     }
 25641                   it->hpos = hpos_before;
 25642                 }
 25643             }
 25644           else if (IT_OVERFLOW_NEWLINE_INTO_FRINGE (it))
 25645             {
 25646               /* Don't truncate if we can overflow newline into fringe.  */
 25647               if (!get_next_display_element (it))
 25648                 {
 25649                   it->continuation_lines_width = 0;
 25650                   it->font_height = Qnil;
 25651                   it->voffset = 0;
 25652                   row->ends_at_zv_p = true;
 25653                   row->exact_window_width_line_p = true;
 25654                   break;
 25655                 }
 25656               if (ITERATOR_AT_END_OF_LINE_P (it))
 25657                 {
 25658                   row->exact_window_width_line_p = true;
 25659                   goto at_end_of_line;
 25660                 }
 25661               it->current_x = x_before;
 25662               it->hpos = hpos_before;
 25663             }
 25664 
 25665           row->truncated_on_right_p = true;
 25666           it->continuation_lines_width = 0;
 25667           reseat_at_next_visible_line_start (it, false);
 25668           /* We insist below that IT's position be at ZV because in
 25669              bidi-reordered lines the character at visible line start
 25670              might not be the character that follows the newline in
 25671              the logical order.  */
 25672           if (IT_BYTEPOS (*it) > BEG_BYTE)
 25673             row->ends_at_zv_p =
 25674               IT_BYTEPOS (*it) >= ZV_BYTE
 25675               && (ZV_BYTE <= 1 || FETCH_BYTE (ZV_BYTE - 1) != '\n');
 25676           else
 25677             row->ends_at_zv_p = false;
 25678           break;
 25679         }
 25680     }
 25681 
 25682   if (wrap_data)
 25683     bidi_unshelve_cache (wrap_data, true);
 25684 
 25685   /* If line is not empty and hscrolled, maybe insert truncation glyphs
 25686      at the left window margin.  */
 25687   if (it->first_visible_x
 25688       && IT_CHARPOS (*it) != CHARPOS (row->start.pos))
 25689     {
 25690       if (!FRAME_WINDOW_P (it->f)
 25691           || (((row->reversed_p
 25692                 ? WINDOW_RIGHT_FRINGE_WIDTH (it->w)
 25693                 : WINDOW_LEFT_FRINGE_WIDTH (it->w)) == 0)
 25694               /* Don't let insert_left_trunc_glyphs overwrite the
 25695                  first glyph of the row if it is an image.  */
 25696               && row->glyphs[TEXT_AREA]->type != IMAGE_GLYPH))
 25697         insert_left_trunc_glyphs (it);
 25698       row->truncated_on_left_p = true;
 25699     }
 25700 
 25701   /* Remember the position at which this line ends.
 25702 
 25703      BIDI Note: any code that needs MATRIX_ROW_START/END_CHARPOS
 25704      cannot be before the call to find_row_edges below, since that is
 25705      where these positions are determined. */
 25706   row->end = it->current;
 25707   if (!it->bidi_p)
 25708     {
 25709       row->minpos = row->start.pos;
 25710       row->maxpos = row->end.pos;
 25711     }
 25712   else
 25713     {
 25714       /* ROW->minpos and ROW->maxpos must be the smallest and
 25715          `1 + the largest' buffer positions in ROW.  But if ROW was
 25716          bidi-reordered, these two positions can be anywhere in the
 25717          row, so we must determine them now.  */
 25718       find_row_edges (it, row, min_pos, min_bpos, max_pos, max_bpos);
 25719     }
 25720 
 25721   /* If the start of this line is the overlay arrow-position, then
 25722      mark this glyph row as the one containing the overlay arrow.
 25723      This is clearly a mess with variable size fonts.  It would be
 25724      better to let it be displayed like cursors under X.  */
 25725   if ((MATRIX_ROW_DISPLAYS_TEXT_P (row) || !overlay_arrow_seen)
 25726       && (overlay_arrow_string = overlay_arrow_at_row (it, row),
 25727           !NILP (overlay_arrow_string)))
 25728     {
 25729       /* Overlay arrow in window redisplay is a fringe bitmap.  */
 25730       if (STRINGP (overlay_arrow_string))
 25731         {
 25732           struct glyph_row *arrow_row
 25733             = get_overlay_arrow_glyph_row (it->w, overlay_arrow_string);
 25734           struct glyph *glyph = arrow_row->glyphs[TEXT_AREA];
 25735           struct glyph *arrow_end = glyph + arrow_row->used[TEXT_AREA];
 25736           struct glyph *p = row->glyphs[TEXT_AREA];
 25737           struct glyph *p2, *end;
 25738 
 25739           /* Copy the arrow glyphs.  */
 25740           while (glyph < arrow_end)
 25741             *p++ = *glyph++;
 25742 
 25743           /* Throw away padding glyphs.  */
 25744           p2 = p;
 25745           end = row->glyphs[TEXT_AREA] + row->used[TEXT_AREA];
 25746           while (p2 < end && CHAR_GLYPH_PADDING_P (*p2))
 25747             ++p2;
 25748           if (p2 > p)
 25749             {
 25750               while (p2 < end)
 25751                 *p++ = *p2++;
 25752               row->used[TEXT_AREA] = p2 - row->glyphs[TEXT_AREA];
 25753             }
 25754         }
 25755       else
 25756         {
 25757           eassert (FIXNUMP (overlay_arrow_string));
 25758           row->overlay_arrow_bitmap = XFIXNUM (overlay_arrow_string);
 25759         }
 25760       overlay_arrow_seen = true;
 25761     }
 25762 
 25763   /* Highlight trailing whitespace.  */
 25764   if (!NILP (Vshow_trailing_whitespace))
 25765     highlight_trailing_whitespace (it);
 25766 
 25767   /* Compute pixel dimensions of this line.  */
 25768   compute_line_metrics (it);
 25769 
 25770   /* Implementation note: No changes in the glyphs of ROW or in their
 25771      faces can be done past this point, because compute_line_metrics
 25772      computes ROW's hash value and stores it within the glyph_row
 25773      structure.  */
 25774 
 25775   /* Record whether this row ends inside an ellipsis.  */
 25776   row->ends_in_ellipsis_p
 25777     = (it->method == GET_FROM_DISPLAY_VECTOR
 25778        && it->ellipsis_p);
 25779 
 25780   /* Save fringe bitmaps in this row.  */
 25781   row->left_user_fringe_bitmap = it->left_user_fringe_bitmap;
 25782   row->left_user_fringe_face_id = it->left_user_fringe_face_id;
 25783   row->right_user_fringe_bitmap = it->right_user_fringe_bitmap;
 25784   row->right_user_fringe_face_id = it->right_user_fringe_face_id;
 25785 
 25786   it->left_user_fringe_bitmap = 0;
 25787   it->left_user_fringe_face_id = 0;
 25788   it->right_user_fringe_bitmap = 0;
 25789   it->right_user_fringe_face_id = 0;
 25790 
 25791   /* When they turn off tooltip-mode on a GUI frame, we call 'message'
 25792      with message-truncate-lines bound to non-nil, which produces
 25793      truncation bitmaps on the fringe.  Force redrawing of the fringes
 25794      in that case, to make sure the fringe bitmaps are removed when a
 25795      shorter message is displayed.  */
 25796   if (MINI_WINDOW_P (it->w) && it->line_wrap == TRUNCATE
 25797       && FRAME_WINDOW_P (it->f) && !cursor_in_echo_area)
 25798     row->redraw_fringe_bitmaps_p = true;
 25799 
 25800   /* Maybe set the cursor.  */
 25801   cvpos = it->w->cursor.vpos;
 25802   if ((cvpos < 0
 25803        /* In bidi-reordered rows, keep checking for proper cursor
 25804           position even if one has been found already, because buffer
 25805           positions in such rows change non-linearly with ROW->VPOS,
 25806           when a line is continued.  One exception: when we are at ZV,
 25807           display cursor on the first suitable glyph row, since all
 25808           the empty rows after that also have their position set to ZV.  */
 25809        /* FIXME: Revisit this when glyph ``spilling'' in continuation
 25810           lines' rows is implemented for bidi-reordered rows.  */
 25811        || (it->bidi_p
 25812            && !MATRIX_ROW (it->w->desired_matrix, cvpos)->ends_at_zv_p))
 25813       && PT >= MATRIX_ROW_START_CHARPOS (row)
 25814       && PT <= MATRIX_ROW_END_CHARPOS (row)
 25815       && cursor_row_p (row))
 25816     set_cursor_from_row (it->w, row, it->w->desired_matrix, 0, 0, 0, 0);
 25817 
 25818   /* Prepare for the next line.  This line starts horizontally at (X
 25819      HPOS) = (0 0).  Vertical positions are incremented.  As a
 25820      convenience for the caller, IT->glyph_row is set to the next
 25821      row to be used.  */
 25822   it->current_x = it->hpos = 0;
 25823   it->current_y += row->height;
 25824   /* Restore the first and last visible X if we adjusted them for
 25825      current-line hscrolling.  */
 25826   if (hscroll_this_line)
 25827     {
 25828       it->first_visible_x = first_visible_x;
 25829       it->last_visible_x  = last_visible_x;
 25830     }
 25831   SET_TEXT_POS (it->eol_pos, 0, 0);
 25832   ++it->vpos;
 25833   ++it->glyph_row;
 25834   /* The next row should by default use the same value of the
 25835      reversed_p flag as this one.  set_iterator_to_next decides when
 25836      it's a new paragraph, and PRODUCE_GLYPHS recomputes the value of
 25837      the flag accordingly.  */
 25838   if (it->glyph_row < MATRIX_BOTTOM_TEXT_ROW (it->w->desired_matrix, it->w))
 25839     it->glyph_row->reversed_p = row->reversed_p;
 25840   it->start = row->end;
 25841   return MATRIX_ROW_DISPLAYS_TEXT_P (row);
 25842 
 25843 #undef RECORD_MAX_MIN_POS
 25844 }
 25845 
 25846 DEFUN ("current-bidi-paragraph-direction", Fcurrent_bidi_paragraph_direction,
 25847        Scurrent_bidi_paragraph_direction, 0, 1, 0,
 25848        doc: /* Return paragraph direction at point in BUFFER.
 25849 Value is either `left-to-right' or `right-to-left'.
 25850 If BUFFER is omitted or nil, it defaults to the current buffer.
 25851 
 25852 Paragraph direction determines how the text in the paragraph is displayed.
 25853 In left-to-right paragraphs, text begins at the left margin of the window
 25854 and the reading direction is generally left to right.  In right-to-left
 25855 paragraphs, text begins at the right margin and is read from right to left.
 25856 
 25857 See also `bidi-paragraph-direction'.  */)
 25858   (Lisp_Object buffer)
 25859 {
 25860   struct buffer *buf = current_buffer;
 25861   struct buffer *old = buf;
 25862 
 25863   if (! NILP (buffer))
 25864     {
 25865       CHECK_BUFFER (buffer);
 25866       buf = XBUFFER (buffer);
 25867     }
 25868 
 25869   if (NILP (BVAR (buf, bidi_display_reordering))
 25870       || NILP (BVAR (buf, enable_multibyte_characters))
 25871       /* When we are loading loadup.el, the character property tables
 25872          needed for bidi iteration are not yet available.  */
 25873       || redisplay__inhibit_bidi)
 25874     return Qleft_to_right;
 25875   else if (!NILP (BVAR (buf, bidi_paragraph_direction)))
 25876     return BVAR (buf, bidi_paragraph_direction);
 25877   else
 25878     {
 25879       /* Determine the direction from buffer text.  We could try to
 25880          use current_matrix if it is up to date, but this seems fast
 25881          enough as it is.  */
 25882       struct bidi_it itb;
 25883       ptrdiff_t pos = BUF_PT (buf);
 25884       ptrdiff_t bytepos = BUF_PT_BYTE (buf);
 25885       int c;
 25886       void *itb_data = bidi_shelve_cache ();
 25887 
 25888       set_buffer_temp (buf);
 25889       /* bidi_paragraph_init finds the base direction of the paragraph
 25890          by searching forward from paragraph start.  We need the base
 25891          direction of the current or _previous_ paragraph, so we need
 25892          to make sure we are within that paragraph.  To that end, find
 25893          the previous non-empty line.  */
 25894       if (pos >= ZV && pos > BEGV)
 25895         dec_both (&pos, &bytepos);
 25896       AUTO_STRING (trailing_white_space, "[\f\t ]*\n");
 25897       if (fast_looking_at (trailing_white_space,
 25898                            pos, bytepos, ZV, ZV_BYTE, Qnil) > 0)
 25899         {
 25900           while ((c = FETCH_BYTE (bytepos)) == '\n'
 25901                  || c == ' ' || c == '\t' || c == '\f')
 25902             {
 25903               if (bytepos <= BEGV_BYTE)
 25904                 break;
 25905               bytepos--;
 25906               pos--;
 25907             }
 25908           while (!CHAR_HEAD_P (FETCH_BYTE (bytepos)))
 25909             bytepos--;
 25910         }
 25911       bidi_init_it (pos, bytepos, FRAME_WINDOW_P (SELECTED_FRAME ()), &itb);
 25912       itb.paragraph_dir = NEUTRAL_DIR;
 25913       itb.string.s = NULL;
 25914       itb.string.lstring = Qnil;
 25915       itb.string.bufpos = 0;
 25916       itb.string.from_disp_str = false;
 25917       itb.string.unibyte = false;
 25918       /* We have no window to use here for ignoring window-specific
 25919          overlays.  Using NULL for window pointer will cause
 25920          compute_display_string_pos to use the current buffer.  */
 25921       itb.w = NULL;
 25922       bidi_paragraph_init (NEUTRAL_DIR, &itb, true);
 25923       bidi_unshelve_cache (itb_data, false);
 25924       set_buffer_temp (old);
 25925       switch (itb.paragraph_dir)
 25926         {
 25927         case L2R:
 25928           return Qleft_to_right;
 25929           break;
 25930         case R2L:
 25931           return Qright_to_left;
 25932           break;
 25933         default:
 25934           emacs_abort ();
 25935         }
 25936     }
 25937 }
 25938 
 25939 DEFUN ("bidi-find-overridden-directionality",
 25940        Fbidi_find_overridden_directionality,
 25941        Sbidi_find_overridden_directionality, 3, 4, 0,
 25942        doc: /* Return position between FROM and TO where directionality was overridden.
 25943 
 25944 This function returns the first character position in the specified
 25945 region of OBJECT where characters have their bidirectional
 25946 properties affected in a way that might make its text look confusingly
 25947 on display.  For example, characters whose `bidi-class' property is `L',
 25948 could be forced to display as `R' by a directional override, and
 25949 likewise characters whose `bidi-class' is `R' or `AL' that are
 25950 forced to display as `L'.
 25951 
 25952 If no such character is found, the function returns nil.
 25953 
 25954 OBJECT is a Lisp string or buffer to search for overridden
 25955 directionality, and defaults to the current buffer if nil.
 25956 OBJECT can also be a window, in which case the function will search
 25957 the buffer displayed in that window.  Passing the window instead of
 25958 a buffer is preferable when the buffer is displayed in some window,
 25959 because this function will then be able to correctly account for
 25960 window-specific overlays, which can affect the results.
 25961 
 25962 Optional argument BASE-DIR specifies the base paragraph directory
 25963 of the text.  It should be a symbol, either `left-to-right'
 25964 or `right-to-left', and defaults to `left-to-right'.
 25965 
 25966 Strong directional characters `L', `R', and `AL' can have their
 25967 intrinsic directionality overridden by directional override control
 25968 characters RLO (u+202E) and LRO (u+202D).  They can also have their
 25969 directionality affected by other formatting control characters: LRE
 25970 (u+202A), RLE (u+202B), LRI (u+2066), and RLI (u+2067).  See the
 25971 function `get-char-code-property' for a way to inquire about the
 25972 `bidi-class' property of a character.  Characters whose intrinsic
 25973 directionality is weak or neutral, such as numbers or punctuation
 25974 characters, can be forced to display in a very different place with
 25975 respect of its surrounding characters, so as to make the surrounding
 25976 text confuse the user regarding what the text says.
 25977 
 25978 Also see the `highlight-confusing-reorderings' function, which can be
 25979 useful in similar circumstances as this function.  */)
 25980   (Lisp_Object from, Lisp_Object to, Lisp_Object object, Lisp_Object base_dir)
 25981 {
 25982   struct buffer *buf = current_buffer;
 25983   struct buffer *old = buf;
 25984   struct window *w = NULL;
 25985   bool frame_window_p = FRAME_WINDOW_P (SELECTED_FRAME ());
 25986   struct bidi_it itb;
 25987   ptrdiff_t from_pos, to_pos, from_bpos;
 25988   void *itb_data;
 25989 
 25990   if (!NILP (object))
 25991     {
 25992       if (BUFFERP (object))
 25993         buf = XBUFFER (object);
 25994       else if (WINDOWP (object))
 25995         {
 25996           w = decode_live_window (object);
 25997           buf = XBUFFER (w->contents);
 25998           frame_window_p = FRAME_WINDOW_P (XFRAME (w->frame));
 25999         }
 26000       else
 26001         CHECK_STRING (object);
 26002     }
 26003 
 26004   if (STRINGP (object))
 26005     {
 26006       /* Characters in unibyte strings are always treated by bidi.c as
 26007          strong LTR.  */
 26008       if (!STRING_MULTIBYTE (object)
 26009           /* When we are loading loadup.el, the character property
 26010              tables needed for bidi iteration are not yet
 26011              available.  */
 26012           || redisplay__inhibit_bidi)
 26013         return Qnil;
 26014 
 26015       validate_subarray (object, from, to, SCHARS (object), &from_pos, &to_pos);
 26016       if (from_pos >= SCHARS (object))
 26017         return Qnil;
 26018 
 26019       /* Set up the bidi iterator.  */
 26020       itb_data = bidi_shelve_cache ();
 26021       itb.paragraph_dir = NEUTRAL_DIR;
 26022       itb.string.lstring = object;
 26023       itb.string.s = NULL;
 26024       itb.string.schars = SCHARS (object);
 26025       itb.string.bufpos = 0;
 26026       itb.string.from_disp_str = false;
 26027       itb.string.unibyte = false;
 26028       itb.w = w;
 26029       bidi_init_it (0, 0, frame_window_p, &itb);
 26030     }
 26031   else
 26032     {
 26033       /* Nothing this fancy can happen in unibyte buffers, or in a
 26034          buffer that disabled reordering, or if FROM is at EOB.  */
 26035       if (NILP (BVAR (buf, bidi_display_reordering))
 26036           || NILP (BVAR (buf, enable_multibyte_characters))
 26037           /* When we are loading loadup.el, the character property
 26038              tables needed for bidi iteration are not yet
 26039              available.  */
 26040           || redisplay__inhibit_bidi)
 26041         return Qnil;
 26042 
 26043       set_buffer_temp (buf);
 26044       validate_region (&from, &to);
 26045       from_pos = XFIXNUM (from);
 26046       to_pos = XFIXNUM (to);
 26047       if (from_pos >= ZV)
 26048         return Qnil;
 26049 
 26050       /* Set up the bidi iterator.  */
 26051       itb_data = bidi_shelve_cache ();
 26052       from_bpos = CHAR_TO_BYTE (from_pos);
 26053       if (from_pos == BEGV)
 26054         {
 26055           itb.charpos = BEGV;
 26056           itb.bytepos = BEGV_BYTE;
 26057         }
 26058       else if (FETCH_BYTE (from_bpos - 1) == '\n')
 26059         {
 26060           itb.charpos = from_pos;
 26061           itb.bytepos = from_bpos;
 26062         }
 26063       else
 26064         itb.charpos = find_newline_no_quit (from_pos, CHAR_TO_BYTE (from_pos),
 26065                                             -1, &itb.bytepos);
 26066       itb.paragraph_dir = NEUTRAL_DIR;
 26067       itb.string.s = NULL;
 26068       itb.string.lstring = Qnil;
 26069       itb.string.bufpos = 0;
 26070       itb.string.from_disp_str = false;
 26071       itb.string.unibyte = false;
 26072       itb.w = w;
 26073       bidi_init_it (itb.charpos, itb.bytepos, frame_window_p, &itb);
 26074     }
 26075 
 26076   ptrdiff_t found;
 26077   bidi_dir_t bdir = EQ (base_dir, Qright_to_left) ? R2L : L2R;
 26078   do {
 26079     bidi_paragraph_init (bdir, &itb, false);
 26080     while ((found = bidi_find_first_overridden (&itb)) < from_pos)
 26081       ;
 26082   } while (found == ZV && itb.ch == '\n' && itb.charpos < to_pos);
 26083 
 26084   bidi_unshelve_cache (itb_data, false);
 26085   set_buffer_temp (old);
 26086 
 26087   return (from_pos <= found && found < to_pos) ? make_fixnum (found) : Qnil;
 26088 }
 26089 
 26090 DEFUN ("move-point-visually", Fmove_point_visually,
 26091        Smove_point_visually, 1, 1, 0,
 26092        doc: /* Move point in the visual order in the specified DIRECTION.
 26093 DIRECTION can be 1, meaning move to the right, or -1, which moves to the
 26094 left.
 26095 
 26096 Value is the new character position of point.  */)
 26097   (Lisp_Object direction)
 26098 {
 26099   struct window *w = XWINDOW (selected_window);
 26100   struct buffer *b = XBUFFER (w->contents);
 26101   struct glyph_row *row;
 26102   int dir;
 26103   Lisp_Object paragraph_dir;
 26104 
 26105 #define ROW_GLYPH_NEWLINE_P(ROW,GLYPH)          \
 26106   (!(ROW)->continued_p                          \
 26107    && NILP ((GLYPH)->object)                    \
 26108    && (GLYPH)->type == CHAR_GLYPH               \
 26109    && (GLYPH)->u.ch == ' '                      \
 26110    && (GLYPH)->charpos >= 0                     \
 26111    && !(GLYPH)->avoid_cursor_p)
 26112 
 26113   CHECK_FIXNUM (direction);
 26114   dir = XFIXNUM (direction);
 26115   if (dir > 0)
 26116     dir = 1;
 26117   else
 26118     dir = -1;
 26119 
 26120   /* If current matrix is up-to-date, we can use the information
 26121      recorded in the glyphs, at least as long as the goal is on the
 26122      screen.  */
 26123   if (w->window_end_valid
 26124       && !windows_or_buffers_changed
 26125       && b
 26126       && !b->clip_changed
 26127       && !b->prevent_redisplay_optimizations_p
 26128       && !window_outdated (w)
 26129       /* We rely below on the cursor coordinates to be up to date, but
 26130          we cannot trust them if some command moved point since the
 26131          last complete redisplay.  */
 26132       && w->last_point == BUF_PT (b)
 26133       && w->cursor.vpos >= 0
 26134       && w->cursor.vpos < w->current_matrix->nrows
 26135       && (row = MATRIX_ROW (w->current_matrix, w->cursor.vpos))->enabled_p)
 26136     {
 26137       struct glyph *g = row->glyphs[TEXT_AREA];
 26138       struct glyph *e = dir > 0 ? g + row->used[TEXT_AREA] : g - 1;
 26139       struct glyph *gpt = g + w->cursor.hpos;
 26140 
 26141       for (g = gpt + dir; (dir > 0 ? g < e : g > e); g += dir)
 26142         {
 26143           if (BUFFERP (g->object) && g->charpos != PT)
 26144             {
 26145               SET_PT (g->charpos);
 26146               w->cursor.vpos = -1;
 26147               return make_fixnum (PT);
 26148             }
 26149           else if (!NILP (g->object) && !EQ (g->object, gpt->object))
 26150             {
 26151               ptrdiff_t new_pos;
 26152 
 26153               if (BUFFERP (gpt->object))
 26154                 {
 26155                   new_pos = PT;
 26156                   if ((gpt->resolved_level - row->reversed_p) % 2 == 0)
 26157                     new_pos += (row->reversed_p ? -dir : dir);
 26158                   else
 26159                     new_pos -= (row->reversed_p ? -dir : dir);
 26160                   new_pos = clip_to_bounds (BEGV, new_pos, ZV);
 26161                   /* If we didn't move, we've hit BEGV or ZV, so we
 26162                      need to signal a suitable error.  */
 26163                   if (new_pos == PT)
 26164                     break;
 26165                 }
 26166               else if (BUFFERP (g->object))
 26167                 new_pos = g->charpos;
 26168               else
 26169                 break;
 26170               SET_PT (new_pos);
 26171               w->cursor.vpos = -1;
 26172               return make_fixnum (PT);
 26173             }
 26174           else if (ROW_GLYPH_NEWLINE_P (row, g))
 26175             {
 26176               /* Glyphs inserted at the end of a non-empty line for
 26177                  positioning the cursor have zero charpos, so we must
 26178                  deduce the value of point by other means.  */
 26179               if (g->charpos > 0)
 26180                 SET_PT (g->charpos);
 26181               else if (row->ends_at_zv_p && PT != ZV)
 26182                 SET_PT (ZV);
 26183               else if (PT != MATRIX_ROW_END_CHARPOS (row) - 1)
 26184                 SET_PT (MATRIX_ROW_END_CHARPOS (row) - 1);
 26185               else
 26186                 break;
 26187               w->cursor.vpos = -1;
 26188               return make_fixnum (PT);
 26189             }
 26190         }
 26191       if (g == e || NILP (g->object))
 26192         {
 26193           if (row->truncated_on_left_p || row->truncated_on_right_p)
 26194             goto simulate_display;
 26195           if (!row->reversed_p)
 26196             row += dir;
 26197           else
 26198             row -= dir;
 26199           if (!(MATRIX_FIRST_TEXT_ROW (w->current_matrix) <= row
 26200                 && row < MATRIX_BOTTOM_TEXT_ROW (w->current_matrix, w)))
 26201             goto simulate_display;
 26202 
 26203           if (dir > 0)
 26204             {
 26205               if (row->reversed_p && !row->continued_p)
 26206                 {
 26207                   SET_PT (MATRIX_ROW_END_CHARPOS (row) - 1);
 26208                   w->cursor.vpos = -1;
 26209                   return make_fixnum (PT);
 26210                 }
 26211               g = row->glyphs[TEXT_AREA];
 26212               e = g + row->used[TEXT_AREA];
 26213               for ( ; g < e; g++)
 26214                 {
 26215                   if (BUFFERP (g->object)
 26216                       /* Empty lines have only one glyph, which stands
 26217                          for the newline, and whose charpos is the
 26218                          buffer position of the newline.  */
 26219                       || ROW_GLYPH_NEWLINE_P (row, g)
 26220                       /* When the buffer ends in a newline, the line at
 26221                          EOB also has one glyph, but its charpos is -1.  */
 26222                       || (row->ends_at_zv_p
 26223                           && !row->reversed_p
 26224                           && NILP (g->object)
 26225                           && g->type == CHAR_GLYPH
 26226                           && g->u.ch == ' '))
 26227                     {
 26228                       if (g->charpos > 0)
 26229                         SET_PT (g->charpos);
 26230                       else if (!row->reversed_p
 26231                                && row->ends_at_zv_p
 26232                                && PT != ZV)
 26233                         SET_PT (ZV);
 26234                       else
 26235                         continue;
 26236                       w->cursor.vpos = -1;
 26237                       return make_fixnum (PT);
 26238                     }
 26239                 }
 26240             }
 26241           else
 26242             {
 26243               if (!row->reversed_p && !row->continued_p)
 26244                 {
 26245                   SET_PT (MATRIX_ROW_END_CHARPOS (row) - 1);
 26246                   w->cursor.vpos = -1;
 26247                   return make_fixnum (PT);
 26248                 }
 26249               e = row->glyphs[TEXT_AREA];
 26250               g = e + row->used[TEXT_AREA] - 1;
 26251               for ( ; g >= e; g--)
 26252                 {
 26253                   if (BUFFERP (g->object)
 26254                       || (ROW_GLYPH_NEWLINE_P (row, g)
 26255                           && g->charpos > 0)
 26256                       /* Empty R2L lines on GUI frames have the buffer
 26257                          position of the newline stored in the stretch
 26258                          glyph.  */
 26259                       || g->type == STRETCH_GLYPH
 26260                       || (row->ends_at_zv_p
 26261                           && row->reversed_p
 26262                           && NILP (g->object)
 26263                           && g->type == CHAR_GLYPH
 26264                           && g->u.ch == ' '))
 26265                     {
 26266                       if (g->charpos > 0)
 26267                         SET_PT (g->charpos);
 26268                       else if (row->reversed_p
 26269                                && row->ends_at_zv_p
 26270                                && PT != ZV)
 26271                         SET_PT (ZV);
 26272                       else
 26273                         continue;
 26274                       w->cursor.vpos = -1;
 26275                       return make_fixnum (PT);
 26276                     }
 26277                 }
 26278             }
 26279         }
 26280     }
 26281 
 26282  simulate_display:
 26283 
 26284   /* If we wind up here, we failed to move by using the glyphs, so we
 26285      need to simulate display instead.  */
 26286 
 26287   if (b)
 26288     paragraph_dir = Fcurrent_bidi_paragraph_direction (w->contents);
 26289   else
 26290     paragraph_dir = Qleft_to_right;
 26291   if (EQ (paragraph_dir, Qright_to_left))
 26292     dir = -dir;
 26293   if (PT <= BEGV && dir < 0)
 26294     xsignal0 (Qbeginning_of_buffer);
 26295   else if (PT >= ZV && dir > 0)
 26296     xsignal0 (Qend_of_buffer);
 26297   else
 26298     {
 26299       struct text_pos pt;
 26300       struct it it;
 26301       int pt_x, target_x, pixel_width, pt_vpos;
 26302       bool at_eol_p;
 26303       bool overshoot_expected = false;
 26304       bool target_is_eol_p = false;
 26305       void *itdata = bidi_shelve_cache ();
 26306 
 26307       /* Setup the arena.  */
 26308       SET_TEXT_POS (pt, PT, PT_BYTE);
 26309       start_display (&it, w, pt);
 26310       /* When lines are truncated, we could be called with point
 26311          outside of the windows edges, in which case move_it_*
 26312          functions either prematurely stop at window's edge or jump to
 26313          the next screen line, whereas we rely below on our ability to
 26314          reach point, in order to start from its X coordinate.  So we
 26315          need to disregard the window's horizontal extent in that case.  */
 26316       if (it.line_wrap == TRUNCATE)
 26317         it.last_visible_x = DISP_INFINITY;
 26318 
 26319       if (it.cmp_it.id < 0
 26320           && it.method == GET_FROM_STRING
 26321           && it.area == TEXT_AREA
 26322           && it.string_from_display_prop_p
 26323           && (it.sp > 0 && it.stack[it.sp - 1].method == GET_FROM_BUFFER))
 26324         overshoot_expected = true;
 26325 
 26326       /* Find the X coordinate of point.  We start from the beginning
 26327          of this or previous line to make sure we are before point in
 26328          the logical order (since the move_it_* functions can only
 26329          move forward).  */
 26330     reseat:
 26331       reseat_at_previous_visible_line_start (&it);
 26332       it.current_x = it.hpos = it.current_y = it.vpos = 0;
 26333       if (IT_CHARPOS (it) != PT)
 26334         {
 26335           move_it_to (&it, overshoot_expected ? PT - 1 : PT,
 26336                       -1, -1, -1, MOVE_TO_POS);
 26337           /* If we missed point because the character there is
 26338              displayed out of a display vector that has more than one
 26339              glyph, retry expecting overshoot.  */
 26340           if (it.method == GET_FROM_DISPLAY_VECTOR
 26341               && it.current.dpvec_index > 0
 26342               && !overshoot_expected)
 26343             {
 26344               overshoot_expected = true;
 26345               goto reseat;
 26346             }
 26347           else if (IT_CHARPOS (it) != PT && !overshoot_expected)
 26348             move_it_in_display_line (&it, PT, -1, MOVE_TO_POS);
 26349         }
 26350       pt_x = it.current_x;
 26351       pt_vpos = it.vpos;
 26352       if (dir > 0 || overshoot_expected)
 26353         {
 26354           struct glyph_row *row = it.glyph_row;
 26355 
 26356           /* When point is at beginning of line, we don't have
 26357              information about the glyph there loaded into struct
 26358              it.  Calling get_next_display_element fixes that.  */
 26359           if (pt_x == 0)
 26360             get_next_display_element (&it);
 26361           at_eol_p = ITERATOR_AT_END_OF_LINE_P (&it);
 26362           it.glyph_row = NULL;
 26363           PRODUCE_GLYPHS (&it); /* compute it.pixel_width */
 26364           it.glyph_row = row;
 26365           /* PRODUCE_GLYPHS advances it.current_x, so we must restore
 26366              it, lest it will become out of sync with it's buffer
 26367              position.  */
 26368           it.current_x = pt_x;
 26369         }
 26370       else
 26371         at_eol_p = ITERATOR_AT_END_OF_LINE_P (&it);
 26372       pixel_width = it.pixel_width;
 26373       if (overshoot_expected && at_eol_p)
 26374         pixel_width = 0;
 26375       else if (pixel_width <= 0)
 26376         pixel_width = 1;
 26377 
 26378       /* If there's a display string (or something similar) at point,
 26379          we are actually at the glyph to the left of point, so we need
 26380          to correct the X coordinate.  */
 26381       if (overshoot_expected)
 26382         {
 26383           if (it.bidi_p)
 26384             pt_x += pixel_width * it.bidi_it.scan_dir;
 26385           else
 26386             pt_x += pixel_width;
 26387         }
 26388 
 26389       /* Compute target X coordinate, either to the left or to the
 26390          right of point.  On TTY frames, all characters have the same
 26391          pixel width of 1, so we can use that.  On GUI frames we don't
 26392          have an easy way of getting at the pixel width of the
 26393          character to the left of point, so we use a different method
 26394          of getting to that place.  */
 26395       if (dir > 0)
 26396         target_x = pt_x + pixel_width;
 26397       else
 26398         target_x = pt_x - (!FRAME_WINDOW_P (it.f)) * pixel_width;
 26399 
 26400       /* Target X coordinate could be one line above or below the line
 26401          of point, in which case we need to adjust the target X
 26402          coordinate.  Also, if moving to the left, we need to begin at
 26403          the left edge of the point's screen line.  */
 26404       if (dir < 0)
 26405         {
 26406           if (pt_x > 0)
 26407             {
 26408               start_display (&it, w, pt);
 26409               if (it.line_wrap == TRUNCATE)
 26410                 it.last_visible_x = DISP_INFINITY;
 26411               reseat_at_previous_visible_line_start (&it);
 26412               it.current_x = it.current_y = it.hpos = 0;
 26413               if (pt_vpos != 0)
 26414                 move_it_by_lines (&it, pt_vpos);
 26415             }
 26416           else
 26417             {
 26418               move_it_by_lines (&it, -1);
 26419               target_x = it.last_visible_x - !FRAME_WINDOW_P (it.f);
 26420               target_is_eol_p = true;
 26421               /* Under word-wrap, we don't know the x coordinate of
 26422                  the last character displayed on the previous line,
 26423                  which immediately precedes the wrap point.  To find
 26424                  out its x coordinate, we try moving to the right
 26425                  margin of the window, which will stop at the wrap
 26426                  point, and then reset target_x to point at the
 26427                  character that precedes the wrap point.  This is not
 26428                  needed on GUI frames, because (see below) there we
 26429                  move from the left margin one grapheme cluster at a
 26430                  time, and stop when we hit the wrap point.  */
 26431               if (!FRAME_WINDOW_P (it.f) && it.line_wrap == WORD_WRAP)
 26432                 {
 26433                   void *it_data = NULL;
 26434                   struct it it2;
 26435 
 26436                   SAVE_IT (it2, it, it_data);
 26437                   move_it_in_display_line_to (&it, ZV, target_x,
 26438                                               MOVE_TO_POS | MOVE_TO_X);
 26439                   /* If we arrived at target_x, that _is_ the last
 26440                      character on the previous line.  */
 26441                   if (it.current_x != target_x)
 26442                     target_x = it.current_x - 1;
 26443                   RESTORE_IT (&it, &it2, it_data);
 26444                 }
 26445             }
 26446         }
 26447       else
 26448         {
 26449           if (at_eol_p
 26450               || (target_x >= it.last_visible_x
 26451                   && it.line_wrap != TRUNCATE))
 26452             {
 26453               if (pt_x > 0)
 26454                 move_it_by_lines (&it, 0);
 26455               move_it_by_lines (&it, 1);
 26456               target_x = 0;
 26457             }
 26458         }
 26459 
 26460       /* Move to the target X coordinate.  */
 26461       /* On GUI frames, as we don't know the X coordinate of the
 26462          character to the left of point, moving point to the left
 26463          requires walking, one grapheme cluster at a time, until we
 26464          find ourself at a place immediately to the left of the
 26465          character at point.  */
 26466       if (FRAME_WINDOW_P (it.f) && dir < 0)
 26467         {
 26468           struct text_pos new_pos;
 26469           enum move_it_result rc = MOVE_X_REACHED;
 26470 
 26471           if (it.current_x == 0)
 26472             get_next_display_element (&it);
 26473           if (it.what == IT_COMPOSITION)
 26474             {
 26475               new_pos.charpos = it.cmp_it.charpos;
 26476               new_pos.bytepos = -1;
 26477             }
 26478           else
 26479             new_pos = it.current.pos;
 26480 
 26481           while (it.current_x + it.pixel_width <= target_x
 26482                  && (rc == MOVE_X_REACHED
 26483                      /* Under word-wrap, move_it_in_display_line_to
 26484                         stops at correct coordinates, but sometimes
 26485                         returns MOVE_POS_MATCH_OR_ZV.  */
 26486                      || (it.line_wrap == WORD_WRAP
 26487                          && rc == MOVE_POS_MATCH_OR_ZV)))
 26488             {
 26489               int new_x = it.current_x + it.pixel_width;
 26490 
 26491               /* For composed characters, we want the position of the
 26492                  first character in the grapheme cluster (usually, the
 26493                  composition's base character), whereas it.current
 26494                  might give us the position of the _last_ one, e.g. if
 26495                  the composition is rendered in reverse due to bidi
 26496                  reordering.  */
 26497               if (it.what == IT_COMPOSITION)
 26498                 {
 26499                   new_pos.charpos = it.cmp_it.charpos;
 26500                   new_pos.bytepos = -1;
 26501                 }
 26502               else
 26503                 new_pos = it.current.pos;
 26504               if (new_x == it.current_x)
 26505                 new_x++;
 26506               rc = move_it_in_display_line_to (&it, ZV, new_x,
 26507                                                MOVE_TO_POS | MOVE_TO_X);
 26508               if (ITERATOR_AT_END_OF_LINE_P (&it) && !target_is_eol_p)
 26509                 break;
 26510             }
 26511           /* The previous position we saw in the loop is the one we
 26512              want.  */
 26513           if (new_pos.bytepos == -1)
 26514             new_pos.bytepos = CHAR_TO_BYTE (new_pos.charpos);
 26515           it.current.pos = new_pos;
 26516         }
 26517       else if (it.current_x != target_x)
 26518         move_it_in_display_line_to (&it, ZV, target_x, MOVE_TO_POS | MOVE_TO_X);
 26519 
 26520       /* If we ended up in a display string that covers point, move to
 26521          buffer position to the right in the visual order.  */
 26522       if (dir > 0)
 26523         {
 26524           while (IT_CHARPOS (it) == PT)
 26525             {
 26526               set_iterator_to_next (&it, false);
 26527               if (!get_next_display_element (&it))
 26528                 break;
 26529             }
 26530         }
 26531 
 26532       /* Move point to that position.  */
 26533       SET_PT_BOTH (IT_CHARPOS (it), IT_BYTEPOS (it));
 26534       bidi_unshelve_cache (itdata, false);
 26535     }
 26536 
 26537   return make_fixnum (PT);
 26538 
 26539 #undef ROW_GLYPH_NEWLINE_P
 26540 }
 26541 
 26542 DEFUN ("bidi-resolved-levels", Fbidi_resolved_levels,
 26543        Sbidi_resolved_levels, 0, 1, 0,
 26544        doc: /* Return the resolved bidirectional levels of characters at VPOS.
 26545 
 26546 The resolved levels are produced by the Emacs bidi reordering engine
 26547 that implements the UBA, the Unicode Bidirectional Algorithm.  Please
 26548 read the Unicode Standard Annex 9 (UAX#9) for background information
 26549 about these levels.
 26550 
 26551 VPOS is the zero-based number of the current window's screen line
 26552 for which to produce the resolved levels.  If VPOS is nil or omitted,
 26553 it defaults to the screen line of point.  If the window displays a
 26554 header line, VPOS of zero will report on the header line, and first
 26555 line of text in the window will have VPOS of 1.
 26556 
 26557 Value is an array of resolved levels, indexed by glyph number.
 26558 Glyphs are numbered from zero starting from the beginning of the
 26559 screen line, i.e. the left edge of the window for left-to-right lines
 26560 and from the right edge for right-to-left lines.  The resolved levels
 26561 are produced only for the window's text area; text in display margins
 26562 is not included.
 26563 
 26564 If the selected window's display is not up-to-date, or if the specified
 26565 screen line does not display text, this function returns nil.  It is
 26566 highly recommended to bind this function to some simple key, like F8,
 26567 in order to avoid these problems.
 26568 
 26569 This function exists mainly for testing the correctness of the
 26570 Emacs UBA implementation, in particular with the test suite.  */)
 26571   (Lisp_Object vpos)
 26572 {
 26573   struct window *w = XWINDOW (selected_window);
 26574   struct buffer *b = XBUFFER (w->contents);
 26575   int nrow;
 26576   struct glyph_row *row;
 26577 
 26578   if (NILP (vpos))
 26579     {
 26580       int d1, d2, d3, d4, d5;
 26581 
 26582       pos_visible_p (w, PT, &d1, &d2, &d3, &d4, &d5, &nrow);
 26583     }
 26584   else
 26585     {
 26586       CHECK_FIXNUM (vpos);
 26587       nrow = XFIXNUM (vpos);
 26588     }
 26589 
 26590   /* We require up-to-date glyph matrix for this window.  */
 26591   if (w->window_end_valid
 26592       && !windows_or_buffers_changed
 26593       && b
 26594       && !b->clip_changed
 26595       && !b->prevent_redisplay_optimizations_p
 26596       && !window_outdated (w)
 26597       && nrow >= 0
 26598       && nrow < w->current_matrix->nrows
 26599       && (row = MATRIX_ROW (w->current_matrix, nrow))->enabled_p
 26600       && MATRIX_ROW_DISPLAYS_TEXT_P (row))
 26601     {
 26602       struct glyph *g, *e, *g1;
 26603       int nglyphs, i;
 26604       Lisp_Object levels;
 26605 
 26606       if (!row->reversed_p)     /* Left-to-right glyph row.  */
 26607         {
 26608           g = g1 = row->glyphs[TEXT_AREA];
 26609           e = g + row->used[TEXT_AREA];
 26610 
 26611           /* Skip over glyphs at the start of the row that was
 26612              generated by redisplay for its own needs.  */
 26613           while (g < e
 26614                  && NILP (g->object)
 26615                  && g->charpos < 0)
 26616             g++;
 26617           g1 = g;
 26618 
 26619           /* Count the "interesting" glyphs in this row.  */
 26620           for (nglyphs = 0; g < e && !NILP (g->object); g++)
 26621             nglyphs++;
 26622 
 26623           /* Create and fill the array.  */
 26624           levels = make_uninit_vector (nglyphs);
 26625           for (i = 0; g1 < g; i++, g1++)
 26626             ASET (levels, i, make_fixnum (g1->resolved_level));
 26627         }
 26628       else                      /* Right-to-left glyph row.  */
 26629         {
 26630           g = row->glyphs[TEXT_AREA] + row->used[TEXT_AREA] - 1;
 26631           e = row->glyphs[TEXT_AREA] - 1;
 26632           while (g > e
 26633                  && NILP (g->object)
 26634                  && g->charpos < 0)
 26635             g--;
 26636           g1 = g;
 26637           for (nglyphs = 0; g > e && !NILP (g->object); g--)
 26638             nglyphs++;
 26639           levels = make_uninit_vector (nglyphs);
 26640           for (i = 0; g1 > g; i++, g1--)
 26641             ASET (levels, i, make_fixnum (g1->resolved_level));
 26642         }
 26643       return levels;
 26644     }
 26645   else
 26646     return Qnil;
 26647 }
 26648 
 26649 
 26650 
 26651 /***********************************************************************
 26652                                Menu Bar
 26653  ***********************************************************************/
 26654 
 26655 /* Redisplay the menu bar in the frame for window W.
 26656 
 26657    The menu bar of X frames that don't have X toolkit support is
 26658    displayed in a special window W->frame->menu_bar_window.
 26659 
 26660    The menu bar of terminal frames is treated specially as far as
 26661    glyph matrices are concerned.  Menu bar lines are not part of
 26662    windows, so the update is done directly on the frame matrix rows
 26663    for the menu bar.  */
 26664 
 26665 static void
 26666 display_menu_bar (struct window *w)
 26667 {
 26668   struct frame *f = XFRAME (WINDOW_FRAME (w));
 26669   struct it it;
 26670   Lisp_Object items;
 26671   int i;
 26672 
 26673   /* Don't do all this for graphical frames.  */
 26674 #ifdef HAVE_NTGUI
 26675   if (FRAME_W32_P (f))
 26676     return;
 26677 #endif
 26678 #if defined (HAVE_PGTK)
 26679   if (FRAME_PGTK_P (f))
 26680     return;
 26681 #endif
 26682 
 26683 #if defined (USE_X_TOOLKIT) || defined (USE_GTK)
 26684   if (FRAME_X_P (f))
 26685     return;
 26686 #endif
 26687 
 26688 #ifdef HAVE_NS
 26689   if (FRAME_NS_P (f))
 26690     return;
 26691 #endif /* HAVE_NS */
 26692 
 26693 #ifdef HAVE_HAIKU
 26694   if (FRAME_HAIKU_P (f))
 26695     return;
 26696 #endif /* HAVE_HAIKU */
 26697 
 26698 #if defined (USE_X_TOOLKIT) || defined (USE_GTK)
 26699   eassert (!FRAME_WINDOW_P (f));
 26700   init_iterator (&it, w, -1, -1, f->desired_matrix->rows, MENU_FACE_ID);
 26701   it.first_visible_x = 0;
 26702   it.last_visible_x = FRAME_PIXEL_WIDTH (f);
 26703 #elif defined (HAVE_X_WINDOWS) || defined (HAVE_ANDROID)
 26704   struct window *menu_window = NULL;
 26705   struct face *face = FACE_FROM_ID (f, MENU_FACE_ID);
 26706 
 26707   if (FRAME_WINDOW_P (f))
 26708     {
 26709       /* Menu bar lines are displayed in the desired matrix of the
 26710          dummy window menu_bar_window.  */
 26711       menu_window = XWINDOW (f->menu_bar_window);
 26712       init_iterator (&it, menu_window, -1, -1,
 26713                      menu_window->desired_matrix->rows,
 26714                      MENU_FACE_ID);
 26715     }
 26716   else
 26717 #endif /* not USE_X_TOOLKIT and not USE_GTK */
 26718     {
 26719       /* This is a TTY frame, i.e. character hpos/vpos are used as
 26720          pixel x/y.  */
 26721       init_iterator (&it, w, -1, -1, f->desired_matrix->rows,
 26722                      MENU_FACE_ID);
 26723       it.first_visible_x = 0;
 26724       it.last_visible_x = FRAME_COLS (f);
 26725     }
 26726 
 26727   /* FIXME: This should be controlled by a user option.  See the
 26728      comments in redisplay_tool_bar and display_mode_line about
 26729      this.  */
 26730   it.paragraph_embedding = L2R;
 26731 
 26732   /* Clear all rows of the menu bar.  */
 26733   for (i = 0; i < FRAME_MENU_BAR_LINES (f); ++i)
 26734     {
 26735       struct glyph_row *row = it.glyph_row + i;
 26736       clear_glyph_row (row);
 26737       row->enabled_p = true;
 26738       row->full_width_p = true;
 26739       row->reversed_p = false;
 26740     }
 26741 
 26742   /* Display all items of the menu bar.  */
 26743   items = FRAME_MENU_BAR_ITEMS (it.f);
 26744   for (i = 0; i < ASIZE (items); i += 4)
 26745     {
 26746       Lisp_Object string;
 26747 
 26748       /* Stop at nil string.  */
 26749       string = AREF (items, i + 1);
 26750       if (NILP (string))
 26751         break;
 26752 
 26753       /* Remember where item was displayed.  */
 26754       ASET (items, i + 3, make_fixnum (it.hpos));
 26755 
 26756       /* Display the item, pad with one space.  */
 26757       if (it.current_x < it.last_visible_x)
 26758         display_string (NULL, string, Qnil, 0, 0, &it,
 26759                         SCHARS (string) + 1, 0, 0, STRING_MULTIBYTE (string));
 26760     }
 26761 
 26762   /* Fill out the line with spaces.  */
 26763   if (it.current_x < it.last_visible_x)
 26764     display_string ("", Qnil, Qnil, 0, 0, &it, -1, 0, 0, -1);
 26765 
 26766   /* Compute the total height of the lines.  */
 26767   compute_line_metrics (&it);
 26768   it.glyph_row->full_width_p = true;
 26769   it.glyph_row->continued_p = false;
 26770   it.glyph_row->truncated_on_left_p = false;
 26771   it.glyph_row->truncated_on_right_p = false;
 26772 
 26773   /* This will break the moment someone tries to add another window
 26774      system that uses the no toolkit menu bar.  Oh well.  At least
 26775      there will be an error, meaning he will correct the ifdef inside
 26776      which `face' is defined.  */
 26777 #if defined HAVE_WINDOW_SYSTEM && !defined HAVE_EXT_MENU_BAR
 26778   /* Make a 3D menu bar have a shadow at its right end.  */
 26779   extend_face_to_end_of_line (&it);
 26780   if (face->box != FACE_NO_BOX)
 26781     {
 26782       struct glyph *last = (it.glyph_row->glyphs[TEXT_AREA]
 26783                             + it.glyph_row->used[TEXT_AREA] - 1);
 26784       int box_thickness = face->box_vertical_line_width;
 26785       last->right_box_line_p = true;
 26786       /* Add back the space for the right box line we subtracted in
 26787          init_iterator, since the right_box_line_p flag will make the
 26788          glyph wider.  We actually add only as much space as is
 26789          available for the last glyph of the menu bar and whatever
 26790          space is left beyond it, since that glyph could be only
 26791          partially visible.  */
 26792       if (box_thickness > 0)
 26793         last->pixel_width += max (0, (box_thickness
 26794                                       - (it.current_x - it.last_visible_x)));
 26795     }
 26796 
 26797   /* With the non-toolkit version, modify the menu bar window height
 26798      accordingly.  */
 26799   if (FRAME_WINDOW_P (it.f) && menu_window)
 26800     {
 26801       struct glyph_row *row;
 26802       int delta_height;
 26803 
 26804       row = it.glyph_row;
 26805       delta_height
 26806         = ((row->y + row->height)
 26807            - WINDOW_BOX_HEIGHT_NO_MODE_LINE (menu_window));
 26808 
 26809       if (delta_height != 0)
 26810         {
 26811           FRAME_MENU_BAR_HEIGHT (it.f) += delta_height;
 26812           adjust_frame_size (it.f, -1, -1, 3, false, Qmenu_bar_lines);
 26813         }
 26814     }
 26815 #endif
 26816 }
 26817 
 26818 /* This code is never used on Android where there are only GUI and
 26819    initial frames.  */
 26820 
 26821 #ifndef HAVE_ANDROID
 26822 
 26823 /* Deep copy of a glyph row, including the glyphs.  */
 26824 static void
 26825 deep_copy_glyph_row (struct glyph_row *to, struct glyph_row *from)
 26826 {
 26827   struct glyph *pointers[1 + LAST_AREA];
 26828   int to_used = to->used[TEXT_AREA];
 26829 
 26830   /* Save glyph pointers of TO.  */
 26831   memcpy (pointers, to->glyphs, sizeof to->glyphs);
 26832 
 26833   /* Do a structure assignment.  */
 26834   *to = *from;
 26835 
 26836   /* Restore original glyph pointers of TO.  */
 26837   memcpy (to->glyphs, pointers, sizeof to->glyphs);
 26838 
 26839   /* Copy the glyphs.  */
 26840   memcpy (to->glyphs[TEXT_AREA], from->glyphs[TEXT_AREA],
 26841           min (from->used[TEXT_AREA], to_used) * sizeof (struct glyph));
 26842 
 26843   /* If we filled only part of the TO row, fill the rest with
 26844      space_glyph (which will display as empty space).  */
 26845   if (to_used > from->used[TEXT_AREA])
 26846     fill_up_frame_row_with_spaces (to, to_used);
 26847 }
 26848 
 26849 /* Display one menu item on a TTY, by overwriting the glyphs in the
 26850    frame F's desired glyph matrix with glyphs produced from the menu
 26851    item text.  Called from term.c to display TTY drop-down menus one
 26852    item at a time.
 26853 
 26854    ITEM_TEXT is the menu item text as a C string.
 26855 
 26856    FACE_ID is the face ID to be used for this menu item.  FACE_ID
 26857    could specify one of 3 faces: a face for an enabled item, a face
 26858    for a disabled item, or a face for a selected item.
 26859 
 26860    X and Y are coordinates of the first glyph in the frame's desired
 26861    matrix to be overwritten by the menu item.  Since this is a TTY, Y
 26862    is the zero-based number of the glyph row and X is the zero-based
 26863    glyph number in the row, starting from left, where to start
 26864    displaying the item.
 26865 
 26866    SUBMENU means this menu item drops down a submenu, which
 26867    should be indicated by displaying a proper visual cue after the
 26868    item text.  */
 26869 
 26870 void
 26871 display_tty_menu_item (const char *item_text, int width, int face_id,
 26872                        int x, int y, bool submenu)
 26873 {
 26874   struct it it;
 26875   struct frame *f = SELECTED_FRAME ();
 26876   struct window *w = XWINDOW (f->selected_window);
 26877   struct glyph_row *row;
 26878   size_t item_len = strlen (item_text);
 26879 
 26880   eassert (FRAME_TERMCAP_P (f));
 26881 
 26882   /* Don't write beyond the matrix's last row.  This can happen for
 26883      TTY screens that are not high enough to show the entire menu.
 26884      (This is actually a bit of defensive programming, as
 26885      tty_menu_display already limits the number of menu items to one
 26886      less than the number of screen lines.)  */
 26887   if (y >= f->desired_matrix->nrows)
 26888     return;
 26889 
 26890   init_iterator (&it, w, -1, -1, f->desired_matrix->rows + y, MENU_FACE_ID);
 26891   it.first_visible_x = 0;
 26892   it.last_visible_x = FRAME_COLS (f) - 1;
 26893   row = it.glyph_row;
 26894   /* Start with the row contents from the current matrix.  */
 26895   deep_copy_glyph_row (row, f->current_matrix->rows + y);
 26896   bool saved_width = row->full_width_p;
 26897   row->full_width_p = true;
 26898   bool saved_reversed = row->reversed_p;
 26899   row->reversed_p = false;
 26900   row->enabled_p = true;
 26901 
 26902   /* Arrange for the menu item glyphs to start at (X,Y) and have the
 26903      desired face.  */
 26904   eassert (x < f->desired_matrix->matrix_w);
 26905   it.current_x = it.hpos = x;
 26906   it.current_y = it.vpos = y;
 26907   int saved_used = row->used[TEXT_AREA];
 26908   bool saved_truncated = row->truncated_on_right_p;
 26909   row->used[TEXT_AREA] = x;
 26910   it.face_id = face_id;
 26911   it.line_wrap = TRUNCATE;
 26912 
 26913   /* FIXME: This should be controlled by a user option.  See the
 26914      comments in redisplay_tool_bar and display_mode_line about this.
 26915      Also, if paragraph_embedding could ever be R2L, changes will be
 26916      needed to avoid shifting to the right the row characters in
 26917      term.c:append_glyph.  */
 26918   it.paragraph_embedding = L2R;
 26919 
 26920   /* Pad with a space on the left.  */
 26921   display_string (" ", Qnil, Qnil, 0, 0, &it, 1, 0, FRAME_COLS (f) - 1, -1);
 26922   width--;
 26923   /* Display the menu item, pad with spaces to WIDTH.  */
 26924   if (submenu)
 26925     {
 26926       display_string (item_text, Qnil, Qnil, 0, 0, &it,
 26927                       item_len, 0, FRAME_COLS (f) - 1, -1);
 26928       width -= item_len;
 26929       /* Indicate with " >" that there's a submenu.  */
 26930       display_string (" >", Qnil, Qnil, 0, 0, &it, width, 0,
 26931                       FRAME_COLS (f) - 1, -1);
 26932     }
 26933   else
 26934     display_string (item_text, Qnil, Qnil, 0, 0, &it,
 26935                     width, 0, FRAME_COLS (f) - 1, -1);
 26936 
 26937   row->used[TEXT_AREA] = max (saved_used, row->used[TEXT_AREA]);
 26938   row->truncated_on_right_p = saved_truncated;
 26939   row->hash = row_hash (row);
 26940   row->full_width_p = saved_width;
 26941   row->reversed_p = saved_reversed;
 26942 }
 26943 
 26944 #endif
 26945 
 26946 
 26947 /***********************************************************************
 26948                               Mode Line
 26949  ***********************************************************************/
 26950 
 26951 /* Redisplay mode lines in the window tree whose root is WINDOW.
 26952    If FORCE, redisplay mode lines unconditionally.
 26953    Otherwise, redisplay only mode lines that are garbaged.  Value is
 26954    the number of windows whose mode lines were redisplayed.  */
 26955 
 26956 static int
 26957 redisplay_mode_lines (Lisp_Object window, bool force)
 26958 {
 26959   int nwindows = 0;
 26960 
 26961   while (!NILP (window))
 26962     {
 26963       struct window *w = XWINDOW (window);
 26964 
 26965       if (WINDOWP (w->contents))
 26966         nwindows += redisplay_mode_lines (w->contents, force);
 26967       else if (force
 26968                || FRAME_GARBAGED_P (XFRAME (w->frame))
 26969                || !MATRIX_MODE_LINE_ROW (w->current_matrix)->enabled_p)
 26970         {
 26971           struct text_pos lpoint;
 26972           struct buffer *old = current_buffer;
 26973 
 26974           /* Set the window's buffer for the mode line display.  */
 26975           SET_TEXT_POS (lpoint, PT, PT_BYTE);
 26976           set_buffer_internal_1 (XBUFFER (w->contents));
 26977 
 26978           /* Point refers normally to the selected window.  For any
 26979              other window, set up appropriate value.  */
 26980           if (!EQ (window, selected_window))
 26981             {
 26982               struct text_pos pt;
 26983 
 26984               CLIP_TEXT_POS_FROM_MARKER (pt, w->pointm);
 26985               TEMP_SET_PT_BOTH (CHARPOS (pt), BYTEPOS (pt));
 26986             }
 26987 
 26988           /* Display mode lines.  */
 26989           clear_glyph_matrix (w->desired_matrix);
 26990           if (display_mode_lines (w))
 26991             ++nwindows;
 26992 
 26993           /* Restore old settings.  */
 26994           set_buffer_internal_1 (old);
 26995           TEMP_SET_PT_BOTH (CHARPOS (lpoint), BYTEPOS (lpoint));
 26996         }
 26997 
 26998       window = w->next;
 26999     }
 27000 
 27001   return nwindows;
 27002 }
 27003 
 27004 
 27005 /* Display the mode line, the header line, and the tab-line of window
 27006    W.  Value is the sum number of mode lines, header lines, and tab
 27007    lines actually displayed.  */
 27008 
 27009 static int
 27010 display_mode_lines (struct window *w)
 27011 {
 27012   Lisp_Object old_selected_window = selected_window;
 27013   Lisp_Object new_frame = w->frame;
 27014   specpdl_ref count = SPECPDL_INDEX ();
 27015   int n = 0;
 27016 
 27017   record_unwind_protect (restore_selected_window, selected_window);
 27018   record_unwind_protect
 27019     (restore_frame_selected_window, XFRAME (new_frame)->selected_window);
 27020 
 27021   if (window_wants_mode_line (w))
 27022     {
 27023       Lisp_Object window;
 27024       Lisp_Object default_help
 27025         = buffer_local_value (Qmode_line_default_help_echo, w->contents);
 27026 
 27027       /* Set up mode line help echo.  Do this before selecting w so it
 27028          can reasonably tell whether a mouse click will select w.  */
 27029       XSETWINDOW (window, w);
 27030       if (FUNCTIONP (default_help))
 27031         wset_mode_line_help_echo (w, safe_call1 (default_help, window));
 27032       else if (STRINGP (default_help))
 27033         wset_mode_line_help_echo (w, default_help);
 27034       else
 27035         wset_mode_line_help_echo (w, Qnil);
 27036     }
 27037 
 27038   selected_frame = new_frame;
 27039   /* FIXME: If we were to allow the mode-line's computation changing the buffer
 27040      or window's point, then we'd need select_window_1 here as well.  */
 27041   XSETWINDOW (selected_window, w);
 27042   XFRAME (new_frame)->selected_window = selected_window;
 27043 
 27044   /* These will be set while the mode line specs are processed.  */
 27045   line_number_displayed = false;
 27046   w->column_number_displayed = -1;
 27047 
 27048   if (window_wants_mode_line (w))
 27049     {
 27050       Lisp_Object window_mode_line_format
 27051         = window_parameter (w, Qmode_line_format);
 27052       struct window *sel_w = XWINDOW (old_selected_window);
 27053 
 27054       /* Select mode line face based on the real selected window.  */
 27055       display_mode_line (w,
 27056                          CURRENT_MODE_LINE_ACTIVE_FACE_ID_3 (sel_w, sel_w, w),
 27057                          NILP (window_mode_line_format)
 27058                          ? BVAR (current_buffer, mode_line_format)
 27059                          : window_mode_line_format);
 27060       ++n;
 27061     }
 27062 
 27063   if (window_wants_tab_line (w))
 27064     {
 27065       Lisp_Object window_tab_line_format
 27066         = window_parameter (w, Qtab_line_format);
 27067 
 27068       display_mode_line (w, TAB_LINE_FACE_ID,
 27069                          NILP (window_tab_line_format)
 27070                          ? BVAR (current_buffer, tab_line_format)
 27071                          : window_tab_line_format);
 27072       ++n;
 27073     }
 27074 
 27075   if (window_wants_header_line (w))
 27076     {
 27077       Lisp_Object window_header_line_format
 27078         = window_parameter (w, Qheader_line_format);
 27079 
 27080       display_mode_line (w, HEADER_LINE_FACE_ID,
 27081                          NILP (window_header_line_format)
 27082                          ? BVAR (current_buffer, header_line_format)
 27083                          : window_header_line_format);
 27084       ++n;
 27085     }
 27086 
 27087   unbind_to (count, Qnil);
 27088 
 27089   if (n > 0)
 27090     w->must_be_updated_p = true;
 27091   return n;
 27092 }
 27093 
 27094 
 27095 /* Display mode or header/tab line of window W.  FACE_ID specifies
 27096    which line to display; it is either MODE_LINE_ACTIVE_FACE_ID,
 27097    HEADER_LINE_FACE_ID or TAB_LINE_FACE_ID.  FORMAT is the
 27098    mode/header/tab line format to display.  Value is the pixel height
 27099    of the mode/header/tab line displayed.  */
 27100 
 27101 static int
 27102 display_mode_line (struct window *w, enum face_id face_id, Lisp_Object format)
 27103 {
 27104   struct it it;
 27105   struct face *face;
 27106   specpdl_ref count = SPECPDL_INDEX ();
 27107 
 27108   init_iterator (&it, w, -1, -1, NULL, face_id);
 27109   /* Don't extend on a previously drawn mode-line.
 27110      This may happen if called from pos_visible_p.  */
 27111   it.glyph_row->enabled_p = false;
 27112   prepare_desired_row (w, it.glyph_row, true);
 27113 
 27114   it.glyph_row->mode_line_p = true;
 27115   if (face_id == TAB_LINE_FACE_ID)
 27116     {
 27117       it.glyph_row->tab_line_p = true;
 27118       w->desired_matrix->tab_line_p = true;
 27119     }
 27120   else if (face_id == HEADER_LINE_FACE_ID)
 27121     w->desired_matrix->header_line_p = true;
 27122 
 27123   /* FIXME: This should be controlled by a user option.  But
 27124      supporting such an option is not trivial, since the mode line is
 27125      made up of many separate strings.  */
 27126   it.paragraph_embedding = L2R;
 27127 
 27128   record_unwind_protect (unwind_format_mode_line,
 27129                          format_mode_line_unwind_data (NULL, NULL,
 27130                                                        Qnil, false));
 27131 
 27132   /* Temporarily make frame's keyboard the current kboard so that
 27133      kboard-local variables in the mode_line_format will get the right
 27134      values.  */
 27135   push_kboard (FRAME_KBOARD (it.f));
 27136   record_unwind_save_match_data ();
 27137 
 27138   if (NILP (Vmode_line_compact)
 27139       || face_id == HEADER_LINE_FACE_ID || face_id == TAB_LINE_FACE_ID)
 27140     {
 27141       mode_line_target = MODE_LINE_DISPLAY;
 27142       display_mode_element (&it, 0, 0, 0, format, Qnil, false);
 27143     }
 27144   else
 27145     {
 27146       Lisp_Object mode_string = Fformat_mode_line (format, Qnil, Qnil, Qnil);
 27147       if (EQ (Vmode_line_compact, Qlong)
 27148           && WINDOW_TOTAL_COLS (w) >= SCHARS (mode_string))
 27149         {
 27150           /* The window is wide enough; just display the mode line we
 27151              just computed. */
 27152           display_string (NULL, mode_string, Qnil,
 27153                           0, 0, &it, 0, 0, 0,
 27154                           STRING_MULTIBYTE (mode_string));
 27155         }
 27156       else
 27157         {
 27158           /* Compress the mode line. */
 27159           ptrdiff_t i = 0, i_byte = 0, start = 0;
 27160           int prev = 0;
 27161 
 27162           while (i < SCHARS (mode_string))
 27163             {
 27164               int c = fetch_string_char_advance (mode_string, &i, &i_byte);
 27165               if (c == ' ' && prev == ' ')
 27166                 {
 27167                   display_string (NULL,
 27168                                   Fsubstring (mode_string, make_fixnum (start),
 27169                                               make_fixnum (i - 1)),
 27170                                   Qnil, 0, 0, &it, 0, 0, 0,
 27171                                   STRING_MULTIBYTE (mode_string));
 27172                   /* Skip past the rest of the space characters. */
 27173                   while (c == ' ' && i < SCHARS (mode_string))
 27174                       c = fetch_string_char_advance (mode_string, &i, &i_byte);
 27175                   start = i - 1;
 27176                 }
 27177               prev = c;
 27178             }
 27179 
 27180           /* Display the final bit. */
 27181           if (start < i)
 27182             display_string (NULL,
 27183                             Fsubstring (mode_string, make_fixnum (start),
 27184                                         make_fixnum (i)),
 27185                             Qnil, 0, 0, &it, 0, 0, 0,
 27186                             STRING_MULTIBYTE (mode_string));
 27187         }
 27188     }
 27189   pop_kboard ();
 27190 
 27191   unbind_to (count, Qnil);
 27192 
 27193   /* Fill up with spaces.  */
 27194   display_string (" ", Qnil, Qnil, 0, 0, &it, 10000, -1, -1, 0);
 27195 
 27196   compute_line_metrics (&it);
 27197   it.glyph_row->full_width_p = true;
 27198   it.glyph_row->continued_p = false;
 27199   it.glyph_row->truncated_on_left_p = false;
 27200   it.glyph_row->truncated_on_right_p = false;
 27201 
 27202   /* Make a 3D mode-line have a shadow at its right end.  */
 27203   face = FACE_FROM_ID (it.f, face_id);
 27204   extend_face_to_end_of_line (&it);
 27205   if (face->box != FACE_NO_BOX)
 27206     {
 27207       struct glyph *last = (it.glyph_row->glyphs[TEXT_AREA]
 27208                             + it.glyph_row->used[TEXT_AREA] - 1);
 27209       int box_thickness = face->box_vertical_line_width;
 27210       last->right_box_line_p = true;
 27211       /* Add back the space for the right box line we subtracted in
 27212          init_iterator, since the right_box_line_p flag will make the
 27213          glyph wider.  We actually add only as much space as is
 27214          available for the last glyph of the modeline and whatever
 27215          space is left beyond it, since that glyph could be only
 27216          partially visible */
 27217       if (box_thickness > 0)
 27218         last->pixel_width += max (0, (box_thickness
 27219                                       - (it.current_x - it.last_visible_x)));
 27220     }
 27221 
 27222   return it.glyph_row->height;
 27223 }
 27224 
 27225 /* Move element ELT in LIST to the front of LIST.
 27226    Return the updated list.  */
 27227 
 27228 static Lisp_Object
 27229 move_elt_to_front (Lisp_Object elt, Lisp_Object list)
 27230 {
 27231   register Lisp_Object tail, prev;
 27232   register Lisp_Object tem;
 27233 
 27234   tail = list;
 27235   prev = Qnil;
 27236   while (CONSP (tail))
 27237     {
 27238       tem = XCAR (tail);
 27239 
 27240       if (EQ (elt, tem))
 27241         {
 27242           /* Splice out the link TAIL.  */
 27243           if (NILP (prev))
 27244             list = XCDR (tail);
 27245           else
 27246             Fsetcdr (prev, XCDR (tail));
 27247 
 27248           /* Now make it the first.  */
 27249           Fsetcdr (tail, list);
 27250           return tail;
 27251         }
 27252       else
 27253         prev = tail;
 27254       tail = XCDR (tail);
 27255       maybe_quit ();
 27256     }
 27257 
 27258   /* Not found--return unchanged LIST.  */
 27259   return list;
 27260 }
 27261 
 27262 /* Subroutine to call Fset_text_properties through
 27263    internal_condition_case_n.  ARGS are the arguments of
 27264    Fset_text_properties, in order.  */
 27265 
 27266 static Lisp_Object
 27267 safe_set_text_properties (ptrdiff_t nargs, Lisp_Object *args)
 27268 {
 27269   eassert (nargs == 4);
 27270   return Fset_text_properties (args[0], args[1], args[2], args[3]);
 27271 }
 27272 
 27273 /* Contribute ELT to the mode line for window IT->w.  How it
 27274    translates into text depends on its data type.
 27275 
 27276    IT describes the display environment in which we display, as usual.
 27277 
 27278    DEPTH is the depth in recursion.  It is used to prevent
 27279    infinite recursion here.
 27280 
 27281    FIELD_WIDTH is the number of characters the display of ELT should
 27282    occupy in the mode line, and PRECISION is the maximum number of
 27283    characters to display from ELT's representation.  See
 27284    display_string for details.
 27285 
 27286    Returns the hpos of the end of the text generated by ELT.
 27287 
 27288    PROPS is a property list to add to any string we encounter.
 27289 
 27290    If RISKY, remove (disregard) any properties in any string
 27291    we encounter, and ignore :eval and :propertize.
 27292 
 27293    The global variable `mode_line_target' determines whether the
 27294    output is passed to `store_mode_line_noprop',
 27295    `store_mode_line_string', or `display_string'.  */
 27296 
 27297 static int
 27298 display_mode_element (struct it *it, int depth, int field_width, int precision,
 27299                       Lisp_Object elt, Lisp_Object props, bool risky)
 27300 {
 27301   int n = 0, field, prec;
 27302   bool literal = false;
 27303 
 27304  tail_recurse:
 27305   if (depth > 100)
 27306     elt = build_string ("*too-deep*");
 27307 
 27308   depth++;
 27309 
 27310   switch (XTYPE (elt))
 27311     {
 27312     case Lisp_String:
 27313       {
 27314         /* A string: output it and check for %-constructs within it.  */
 27315         unsigned char c;
 27316         ptrdiff_t offset = 0;
 27317 
 27318         if (SCHARS (elt) > 0
 27319             && (!NILP (props) || risky))
 27320           {
 27321             Lisp_Object oprops, aelt;
 27322             oprops = Ftext_properties_at (make_fixnum (0), elt);
 27323 
 27324             /* If the starting string's properties are not what
 27325                we want, translate the string.  Also, if the string
 27326                is risky, do that anyway.  */
 27327 
 27328             if (NILP (Fequal (props, oprops)) || risky)
 27329               {
 27330                 /* If the starting string has properties,
 27331                    merge the specified ones onto the existing ones.  */
 27332                 if (! NILP (oprops) && !risky)
 27333                   {
 27334                     Lisp_Object tem;
 27335 
 27336                     oprops = Fcopy_sequence (oprops);
 27337                     tem = props;
 27338                     while (CONSP (tem))
 27339                       {
 27340                         oprops = plist_put (oprops, XCAR (tem),
 27341                                             XCAR (XCDR (tem)));
 27342                         tem = XCDR (XCDR (tem));
 27343                       }
 27344                     props = oprops;
 27345                   }
 27346 
 27347                 aelt = Fassoc (elt, mode_line_proptrans_alist, Qnil);
 27348                 if (! NILP (aelt) && !NILP (Fequal (props, XCDR (aelt))))
 27349                   {
 27350                     /* AELT is what we want.  Move it to the front
 27351                        without consing.  */
 27352                     elt = XCAR (aelt);
 27353                     mode_line_proptrans_alist
 27354                       = move_elt_to_front (aelt, mode_line_proptrans_alist);
 27355                   }
 27356                 else
 27357                   {
 27358                     Lisp_Object tem;
 27359 
 27360                     /* If AELT has the wrong props, it is useless.
 27361                        so get rid of it.  */
 27362                     if (! NILP (aelt))
 27363                       mode_line_proptrans_alist
 27364                         = Fdelq (aelt, mode_line_proptrans_alist);
 27365 
 27366                     elt = Fcopy_sequence (elt);
 27367                     /* PROPS might cause set-text-properties to signal
 27368                        an error, so we call it via internal_condition_case_n,
 27369                        to avoid an infloop in redisplay due to the error.  */
 27370                     internal_condition_case_n (safe_set_text_properties,
 27371                                                4,
 27372                                                ((Lisp_Object [])
 27373                                                {make_fixnum (0),
 27374                                                    Flength (elt),
 27375                                                    props,
 27376                                                    elt}),
 27377                                                Qt, safe_eval_handler);
 27378                     /* Add this item to mode_line_proptrans_alist.  */
 27379                     mode_line_proptrans_alist
 27380                       = Fcons (Fcons (elt, props),
 27381                                mode_line_proptrans_alist);
 27382                     /* Truncate mode_line_proptrans_alist
 27383                        to at most 50 elements.  */
 27384                     tem = Fnthcdr (make_fixnum (50),
 27385                                    mode_line_proptrans_alist);
 27386                     if (! NILP (tem))
 27387                       XSETCDR (tem, Qnil);
 27388                   }
 27389               }
 27390           }
 27391 
 27392         offset = 0;
 27393 
 27394         if (literal)
 27395           {
 27396             prec = precision - n;
 27397             switch (mode_line_target)
 27398               {
 27399               case MODE_LINE_NOPROP:
 27400               case MODE_LINE_TITLE:
 27401                 n += store_mode_line_noprop (SSDATA (elt), -1, prec);
 27402                 break;
 27403               case MODE_LINE_STRING:
 27404                 n += store_mode_line_string (NULL, elt, true, 0, prec, Qnil);
 27405                 break;
 27406               case MODE_LINE_DISPLAY:
 27407                 n += display_string (NULL, elt, Qnil, 0, 0, it,
 27408                                      0, prec, 0, STRING_MULTIBYTE (elt));
 27409                 break;
 27410               }
 27411 
 27412             break;
 27413           }
 27414 
 27415         /* Handle the non-literal case.  */
 27416 
 27417         while ((precision <= 0 || n < precision)
 27418                && SREF (elt, offset) != 0
 27419                && (mode_line_target != MODE_LINE_DISPLAY
 27420                    || it->current_x < it->last_visible_x))
 27421           {
 27422             ptrdiff_t last_offset = offset;
 27423 
 27424             /* Advance to end of string or next format specifier.  */
 27425             while ((c = SREF (elt, offset++)) != '\0' && c != '%')
 27426               ;
 27427 
 27428             if (offset - 1 != last_offset)
 27429               {
 27430                 ptrdiff_t nchars, nbytes;
 27431 
 27432                 /* Output to end of string or up to '%'.  Field width
 27433                    is length of string.  Don't output more than
 27434                    PRECISION allows us.  */
 27435                 offset--;
 27436 
 27437                 prec = c_string_width (SDATA (elt) + last_offset,
 27438                                        offset - last_offset, precision - n,
 27439                                        &nchars, &nbytes);
 27440 
 27441                 switch (mode_line_target)
 27442                   {
 27443                   case MODE_LINE_NOPROP:
 27444                   case MODE_LINE_TITLE:
 27445                     n += store_mode_line_noprop (SSDATA (elt) + last_offset, 0, prec);
 27446                     break;
 27447                   case MODE_LINE_STRING:
 27448                     {
 27449                       ptrdiff_t bytepos = last_offset;
 27450                       ptrdiff_t charpos = string_byte_to_char (elt, bytepos);
 27451                       ptrdiff_t endpos = (precision <= 0
 27452                                           ? string_byte_to_char (elt, offset)
 27453                                           : charpos + nchars);
 27454                       Lisp_Object mode_string
 27455                         = Fsubstring (elt, make_fixnum (charpos),
 27456                                       make_fixnum (endpos));
 27457                       n += store_mode_line_string (NULL, mode_string, false,
 27458                                                    0, 0, Qnil);
 27459                     }
 27460                     break;
 27461                   case MODE_LINE_DISPLAY:
 27462                     {
 27463                       ptrdiff_t bytepos = last_offset;
 27464                       ptrdiff_t charpos = string_byte_to_char (elt, bytepos);
 27465 
 27466                       if (precision <= 0)
 27467                         nchars = string_byte_to_char (elt, offset) - charpos;
 27468                       n += display_string (NULL, elt, Qnil, 0, charpos,
 27469                                            it, 0, nchars, 0,
 27470                                            STRING_MULTIBYTE (elt));
 27471                     }
 27472                     break;
 27473                   }
 27474               }
 27475             else /* c == '%' */
 27476               {
 27477                 ptrdiff_t percent_position = offset;
 27478 
 27479                 /* Get the specified minimum width.  Zero means
 27480                    don't pad.  */
 27481                 field = 0;
 27482                 while ((c = SREF (elt, offset++)) >= '0' && c <= '9')
 27483                   field = field * 10 + c - '0';
 27484 
 27485                 /* Don't pad beyond the total padding allowed.  */
 27486                 if (field_width - n > 0 && field > field_width - n)
 27487                   field = field_width - n;
 27488 
 27489                 /* Note that either PRECISION <= 0 or N < PRECISION.  */
 27490                 prec = precision - n;
 27491 
 27492                 if (c == 'M')
 27493                   n += display_mode_element (it, depth, field, prec,
 27494                                              Vglobal_mode_string, props,
 27495                                              risky);
 27496                 else if (c != 0)
 27497                   {
 27498                     bool multibyte;
 27499                     ptrdiff_t bytepos, charpos;
 27500                     const char *spec;
 27501                     Lisp_Object string;
 27502 
 27503                     bytepos = percent_position;
 27504                     charpos = (STRING_MULTIBYTE (elt)
 27505                                ? string_byte_to_char (elt, bytepos)
 27506                                : bytepos);
 27507                     spec = decode_mode_spec (it->w, c, field, &string);
 27508                     eassert (NILP (string) || STRINGP (string));
 27509                     multibyte = !NILP (string) && STRING_MULTIBYTE (string);
 27510                     /* Non-ASCII characters in SPEC should cause mode-line
 27511                        element be displayed as a multibyte string.  */
 27512                     ptrdiff_t nbytes = strlen (spec);
 27513                     ptrdiff_t nchars, mb_nbytes;
 27514                     parse_str_as_multibyte ((const unsigned char *)spec, nbytes,
 27515                                             &nchars, &mb_nbytes);
 27516                     if (!(nbytes == nchars || nbytes != mb_nbytes))
 27517                       multibyte = true;
 27518 
 27519                     switch (mode_line_target)
 27520                       {
 27521                       case MODE_LINE_NOPROP:
 27522                       case MODE_LINE_TITLE:
 27523                         n += store_mode_line_noprop (spec, field, prec);
 27524                         break;
 27525                       case MODE_LINE_STRING:
 27526                         {
 27527                           Lisp_Object tem = build_string (spec);
 27528                           props = Ftext_properties_at (make_fixnum (charpos), elt);
 27529                           /* Should only keep face property in props */
 27530                           n += store_mode_line_string (NULL, tem, false,
 27531                                                        field, prec, props);
 27532                         }
 27533                         break;
 27534                       case MODE_LINE_DISPLAY:
 27535                         {
 27536                           int nglyphs_before, nwritten;
 27537 
 27538                           nglyphs_before = it->glyph_row->used[TEXT_AREA];
 27539                           nwritten = display_string (spec, string, elt,
 27540                                                      charpos, 0, it,
 27541                                                      field, prec, 0,
 27542                                                      multibyte);
 27543 
 27544                           /* Assign to the glyphs written above the
 27545                              string where the `%x' came from, position
 27546                              of the `%'.  */
 27547                           if (nwritten > 0)
 27548                             {
 27549                               struct glyph *glyph
 27550                                 = (it->glyph_row->glyphs[TEXT_AREA]
 27551                                    + nglyphs_before);
 27552                               int i;
 27553 
 27554                               for (i = 0; i < nwritten; ++i)
 27555                                 {
 27556                                   glyph[i].object = elt;
 27557                                   glyph[i].charpos = charpos;
 27558                                 }
 27559 
 27560                               n += nwritten;
 27561                             }
 27562                         }
 27563                         break;
 27564                       }
 27565                   }
 27566                 else /* c == 0 */
 27567                   break;
 27568               }
 27569           }
 27570       }
 27571       break;
 27572 
 27573     case Lisp_Symbol:
 27574       /* A symbol: process the value of the symbol recursively
 27575          as if it appeared here directly.  Avoid error if symbol void.
 27576          Special case: if value of symbol is a string, output the string
 27577          literally.  */
 27578       {
 27579         register Lisp_Object tem;
 27580 
 27581         /* If the variable is not marked as risky to set
 27582            then its contents are risky to use.  */
 27583         if (NILP (Fget (elt, Qrisky_local_variable)))
 27584           risky = true;
 27585 
 27586         tem = Fboundp (elt);
 27587         if (!NILP (tem))
 27588           {
 27589             tem = Fsymbol_value (elt);
 27590             /* If value is a string, output that string literally:
 27591                don't check for % within it.  */
 27592             if (STRINGP (tem))
 27593               literal = true;
 27594 
 27595             if (!EQ (tem, elt))
 27596               {
 27597                 /* Give up right away for nil or t.  */
 27598                 elt = tem;
 27599                 goto tail_recurse;
 27600               }
 27601           }
 27602       }
 27603       break;
 27604 
 27605     case Lisp_Cons:
 27606       {
 27607         register Lisp_Object car, tem;
 27608 
 27609         /* A cons cell: five distinct cases.
 27610            If first element is :eval or :propertize, do something special.
 27611            If first element is a string or a cons, process all the elements
 27612            and effectively concatenate them.
 27613            If first element is a negative number, truncate displaying cdr to
 27614            at most that many characters.  If positive, pad (with spaces)
 27615            to at least that many characters.
 27616            If first element is a symbol, process the cadr or caddr recursively
 27617            according to whether the symbol's value is non-nil or nil.  */
 27618         car = XCAR (elt);
 27619         if (EQ (car, QCeval))
 27620           {
 27621             /* An element of the form (:eval FORM) means evaluate FORM
 27622                and use the result as mode line elements.  */
 27623 
 27624             if (risky)
 27625               break;
 27626 
 27627             if (CONSP (XCDR (elt)))
 27628               {
 27629                 Lisp_Object spec;
 27630                 spec = safe__eval (true, XCAR (XCDR (elt)));
 27631                 /* The :eval form could delete the frame stored in the
 27632                    iterator, which will cause a crash if we try to
 27633                    access faces and other fields (e.g., FRAME_KBOARD)
 27634                    on that frame.  This is a nonsensical thing to do,
 27635                    and signaling an error from redisplay might be
 27636                    dangerous, but we cannot continue with an invalid frame.  */
 27637                 if (!FRAME_LIVE_P (it->f))
 27638                   signal_error (":eval deleted the frame being displayed", elt);
 27639                 n += display_mode_element (it, depth, field_width - n,
 27640                                            precision - n, spec, props,
 27641                                            risky);
 27642               }
 27643           }
 27644         else if (EQ (car, QCpropertize))
 27645           {
 27646             /* An element of the form (:propertize ELT PROPS...)
 27647                means display ELT but applying properties PROPS.  */
 27648 
 27649             if (risky)
 27650               break;
 27651 
 27652             if (CONSP (XCDR (elt)))
 27653               n += display_mode_element (it, depth, field_width - n,
 27654                                          precision - n, XCAR (XCDR (elt)),
 27655                                          XCDR (XCDR (elt)), risky);
 27656           }
 27657         else if (SYMBOLP (car))
 27658           {
 27659             tem = Fboundp (car);
 27660             elt = XCDR (elt);
 27661             if (!CONSP (elt))
 27662               goto invalid;
 27663             /* elt is now the cdr, and we know it is a cons cell.
 27664                Use its car if CAR has a non-nil value.  */
 27665             if (!NILP (tem))
 27666               {
 27667                 tem = Fsymbol_value (car);
 27668                 if (!NILP (tem))
 27669                   {
 27670                     elt = XCAR (elt);
 27671                     goto tail_recurse;
 27672                   }
 27673               }
 27674             /* Symbol's value is nil (or symbol is unbound)
 27675                Get the cddr of the original list
 27676                and if possible find the caddr and use that.  */
 27677             elt = XCDR (elt);
 27678             if (NILP (elt))
 27679               break;
 27680             else if (!CONSP (elt))
 27681               goto invalid;
 27682             elt = XCAR (elt);
 27683             goto tail_recurse;
 27684           }
 27685         else if (FIXNUMP (car))
 27686           {
 27687             register int lim = XFIXNUM (car);
 27688             elt = XCDR (elt);
 27689             if (lim < 0)
 27690               {
 27691                 /* Negative int means reduce maximum width.  */
 27692                 if (precision <= 0)
 27693                   precision = -lim;
 27694                 else
 27695                   precision = min (precision, -lim);
 27696               }
 27697             else if (lim > 0)
 27698               {
 27699                 /* Padding specified.  Don't let it be more than
 27700                    current maximum.  */
 27701                 if (precision > 0)
 27702                   lim = min (precision, lim);
 27703 
 27704                 /* If that's more padding than already wanted, queue it.
 27705                    But don't reduce padding already specified even if
 27706                    that is beyond the current truncation point.  */
 27707                 field_width = max (lim, field_width);
 27708               }
 27709             goto tail_recurse;
 27710           }
 27711         else if (STRINGP (car) || CONSP (car))
 27712           FOR_EACH_TAIL_SAFE (elt)
 27713             {
 27714               if (0 < precision && precision <= n)
 27715                 break;
 27716               n += display_mode_element (it, depth,
 27717                                          /* Pad after only the last
 27718                                             list element.  */
 27719                                          (! CONSP (XCDR (elt))
 27720                                           ? field_width - n
 27721                                           : 0),
 27722                                          precision - n, XCAR (elt),
 27723                                          props, risky);
 27724             }
 27725       }
 27726       break;
 27727 
 27728     default:
 27729     invalid:
 27730       elt = build_string ("*invalid*");
 27731       goto tail_recurse;
 27732     }
 27733 
 27734   /* Pad to FIELD_WIDTH.  */
 27735   if (field_width > 0 && n < field_width)
 27736     {
 27737       switch (mode_line_target)
 27738         {
 27739         case MODE_LINE_NOPROP:
 27740         case MODE_LINE_TITLE:
 27741           n += store_mode_line_noprop ("", field_width - n, 0);
 27742           break;
 27743         case MODE_LINE_STRING:
 27744           n += store_mode_line_string ("", Qnil, false, field_width - n, 0,
 27745                                        Qnil);
 27746           break;
 27747         case MODE_LINE_DISPLAY:
 27748           n += display_string ("", Qnil, Qnil, 0, 0, it, field_width - n,
 27749                                0, 0, 0);
 27750           break;
 27751         }
 27752     }
 27753 
 27754   return n;
 27755 }
 27756 
 27757 /* Store a mode-line string element in mode_line_string_list.
 27758 
 27759    If STRING is non-null, display that C string.  Otherwise, the Lisp
 27760    string LISP_STRING is displayed.
 27761 
 27762    FIELD_WIDTH is the minimum number of output glyphs to produce.
 27763    If STRING has fewer characters than FIELD_WIDTH, pad to the right
 27764    with spaces.  FIELD_WIDTH <= 0 means don't pad.
 27765 
 27766    PRECISION is the maximum number of characters to output from
 27767    STRING.  PRECISION <= 0  means don't truncate the string.
 27768 
 27769    If COPY_STRING, make a copy of LISP_STRING before adding
 27770    properties to the string.
 27771 
 27772    PROPS are the properties to add to the string.
 27773    The mode_line_string_face face property is always added to the string.
 27774  */
 27775 
 27776 static int
 27777 store_mode_line_string (const char *string, Lisp_Object lisp_string,
 27778                         bool copy_string,
 27779                         int field_width, int precision, Lisp_Object props)
 27780 {
 27781   ptrdiff_t len;
 27782   int n = 0;
 27783 
 27784   if (string != NULL)
 27785     {
 27786       len = strnlen (string, precision <= 0 ? SIZE_MAX : precision);
 27787       lisp_string = make_string (string, len);
 27788       if (NILP (props))
 27789         props = mode_line_string_face_prop;
 27790       else if (!NILP (mode_line_string_face))
 27791         {
 27792           Lisp_Object face = plist_get (props, Qface);
 27793           props = Fcopy_sequence (props);
 27794           if (NILP (face))
 27795             face = mode_line_string_face;
 27796           else
 27797             face = list2 (face, mode_line_string_face);
 27798           props = plist_put (props, Qface, face);
 27799         }
 27800       Fadd_text_properties (make_fixnum (0), make_fixnum (len),
 27801                             props, lisp_string);
 27802     }
 27803   else
 27804     {
 27805       len = SCHARS (lisp_string);
 27806       if (precision > 0 && len > precision)
 27807         {
 27808           len = precision;
 27809           lisp_string = Fsubstring (lisp_string, make_fixnum (0), make_fixnum (len));
 27810           precision = -1;
 27811         }
 27812       if (!NILP (mode_line_string_face))
 27813         {
 27814           Lisp_Object face;
 27815           if (NILP (props))
 27816             props = Ftext_properties_at (make_fixnum (0), lisp_string);
 27817           face = plist_get (props, Qface);
 27818           if (NILP (face))
 27819             face = mode_line_string_face;
 27820           else
 27821             face = list2 (face, mode_line_string_face);
 27822           props = list2 (Qface, face);
 27823           if (copy_string)
 27824             lisp_string = Fcopy_sequence (lisp_string);
 27825         }
 27826       if (!NILP (props))
 27827         Fadd_text_properties (make_fixnum (0), make_fixnum (len),
 27828                               props, lisp_string);
 27829     }
 27830 
 27831   if (len > 0)
 27832     {
 27833       mode_line_string_list = Fcons (lisp_string, mode_line_string_list);
 27834       n += len;
 27835     }
 27836 
 27837   if (field_width > len)
 27838     {
 27839       field_width -= len;
 27840       lisp_string = Fmake_string (make_fixnum (field_width), make_fixnum (' '),
 27841                                   Qnil);
 27842       if (!NILP (props))
 27843         Fadd_text_properties (make_fixnum (0), make_fixnum (field_width),
 27844                               props, lisp_string);
 27845       mode_line_string_list = Fcons (lisp_string, mode_line_string_list);
 27846       n += field_width;
 27847     }
 27848 
 27849   return n;
 27850 }
 27851 
 27852 
 27853 DEFUN ("format-mode-line", Fformat_mode_line, Sformat_mode_line,
 27854        1, 4, 0,
 27855        doc: /* Format a string out of a mode line format specification.
 27856 First arg FORMAT specifies the mode line format (see `mode-line-format'
 27857 for details) to use.
 27858 
 27859 By default, the format is evaluated for the currently selected window.
 27860 
 27861 Optional second arg FACE specifies the face property to put on all
 27862 characters for which no face is specified.  The value nil means the
 27863 default face.  The value t means whatever face the window's mode line
 27864 currently uses (either `mode-line' or `mode-line-inactive',
 27865 depending on whether the window is the selected window or not).
 27866 An integer value means the value string has no text
 27867 properties.
 27868 
 27869 Optional third and fourth args WINDOW and BUFFER specify the window
 27870 and buffer to use as the context for the formatting (defaults
 27871 are the selected window and the WINDOW's buffer).  */)
 27872      (Lisp_Object format, Lisp_Object face,
 27873       Lisp_Object window, Lisp_Object buffer)
 27874 {
 27875   struct it it;
 27876   int len;
 27877   struct window *w;
 27878   struct buffer *old_buffer = NULL;
 27879   int face_id;
 27880   bool no_props = FIXNUMP (face);
 27881   specpdl_ref count = SPECPDL_INDEX ();
 27882   Lisp_Object str;
 27883   int string_start = 0;
 27884 
 27885   w = decode_any_window (window);
 27886   XSETWINDOW (window, w);
 27887 
 27888   if (NILP (buffer))
 27889     buffer = w->contents;
 27890   CHECK_BUFFER (buffer);
 27891 
 27892   /* Make formatting the modeline a non-op when noninteractive, otherwise
 27893      there will be problems later caused by a partially initialized frame.  */
 27894   if (NILP (format) || noninteractive)
 27895     return empty_unibyte_string;
 27896 
 27897   if (no_props)
 27898     face = Qnil;
 27899 
 27900   face_id = (NILP (face) || EQ (face, Qdefault)) ? DEFAULT_FACE_ID
 27901     : EQ (face, Qt) ? (EQ (window, selected_window)
 27902                        ? MODE_LINE_ACTIVE_FACE_ID : MODE_LINE_INACTIVE_FACE_ID)
 27903     : EQ (face, Qmode_line_active) ? MODE_LINE_ACTIVE_FACE_ID
 27904     : EQ (face, Qmode_line_inactive) ? MODE_LINE_INACTIVE_FACE_ID
 27905     : EQ (face, Qheader_line) ? HEADER_LINE_FACE_ID
 27906     : EQ (face, Qtab_line) ? TAB_LINE_FACE_ID
 27907     : EQ (face, Qtab_bar) ? TAB_BAR_FACE_ID
 27908     : EQ (face, Qtool_bar) ? TOOL_BAR_FACE_ID
 27909     : DEFAULT_FACE_ID;
 27910 
 27911   old_buffer = current_buffer;
 27912 
 27913   /* Save things including mode_line_proptrans_alist,
 27914      and set that to nil so that we don't alter the outer value.  */
 27915   record_unwind_protect (unwind_format_mode_line,
 27916                          format_mode_line_unwind_data
 27917                            (XFRAME (WINDOW_FRAME (w)),
 27918                             old_buffer, selected_window, true));
 27919   mode_line_proptrans_alist = Qnil;
 27920 
 27921   Fselect_window (window, Qt);
 27922   set_buffer_internal_1 (XBUFFER (buffer));
 27923 
 27924   init_iterator (&it, w, -1, -1, NULL, face_id);
 27925 
 27926   if (no_props)
 27927     {
 27928       mode_line_target = MODE_LINE_NOPROP;
 27929       mode_line_string_face_prop = Qnil;
 27930       mode_line_string_list = Qnil;
 27931       string_start = MODE_LINE_NOPROP_LEN (0);
 27932     }
 27933   else
 27934     {
 27935       mode_line_target = MODE_LINE_STRING;
 27936       mode_line_string_list = Qnil;
 27937       mode_line_string_face = face;
 27938       mode_line_string_face_prop
 27939         = NILP (face) ? Qnil : list2 (Qface, face);
 27940     }
 27941 
 27942   push_kboard (FRAME_KBOARD (it.f));
 27943   display_mode_element (&it, 0, 0, 0, format, Qnil, false);
 27944   pop_kboard ();
 27945 
 27946   if (no_props)
 27947     {
 27948       len = MODE_LINE_NOPROP_LEN (string_start);
 27949       str = make_string (mode_line_noprop_buf + string_start, len);
 27950     }
 27951   else
 27952     {
 27953       mode_line_string_list = Fnreverse (mode_line_string_list);
 27954       str = Fmapconcat (Qidentity, mode_line_string_list,
 27955                         empty_unibyte_string);
 27956     }
 27957 
 27958   return unbind_to (count, str);
 27959 }
 27960 
 27961 /* Write a null-terminated, right justified decimal representation of
 27962    the positive integer D to BUF using a minimal field width WIDTH.  */
 27963 
 27964 static void
 27965 pint2str (register char *buf, register int width, register ptrdiff_t d)
 27966 {
 27967   register char *p = buf;
 27968 
 27969   if (d <= 0)
 27970     *p++ = '0';
 27971   else
 27972     {
 27973       while (d > 0)
 27974         {
 27975           *p++ = d % 10 + '0';
 27976           d /= 10;
 27977         }
 27978     }
 27979 
 27980   for (width -= (int) (p - buf); width > 0; --width)
 27981     *p++ = ' ';
 27982   *p-- = '\0';
 27983   while (p > buf)
 27984     {
 27985       d = *buf;
 27986       *buf++ = *p;
 27987       *p-- = d;
 27988     }
 27989 }
 27990 
 27991 /* Write a null-terminated, right justified decimal and "human
 27992    readable" representation of the nonnegative integer D to BUF using
 27993    a minimal field width WIDTH.  D should be smaller than 999.5e24. */
 27994 
 27995 static const char power_letter[] =
 27996   {
 27997     0,   /* no letter */
 27998     'k', /* kilo */
 27999     'M', /* mega */
 28000     'G', /* giga */
 28001     'T', /* tera */
 28002     'P', /* peta */
 28003     'E', /* exa */
 28004     'Z', /* zetta */
 28005     'Y', /* yotta */
 28006     'R', /* ronna */
 28007     'Q'  /* quetta */
 28008   };
 28009 
 28010 static void
 28011 pint2hrstr (char *buf, int width, ptrdiff_t d)
 28012 {
 28013   /* We aim to represent the nonnegative integer D as
 28014      QUOTIENT.TENTHS * 10 ^ (3 * EXPONENT). */
 28015   ptrdiff_t quotient = d;
 28016   int remainder = 0;
 28017   /* -1 means: do not use TENTHS. */
 28018   int tenths = -1;
 28019   int exponent = 0;
 28020 
 28021   /* Length of QUOTIENT.TENTHS as a string. */
 28022   int length;
 28023 
 28024   char * psuffix;
 28025   char * p;
 28026 
 28027   if (quotient >= 1000)
 28028     {
 28029       /* Scale to the appropriate EXPONENT. */
 28030       do
 28031         {
 28032           remainder = quotient % 1000;
 28033           quotient /= 1000;
 28034           exponent++;
 28035         }
 28036       while (quotient >= 1000);
 28037 
 28038       /* Round to nearest and decide whether to use TENTHS or not. */
 28039       if (quotient <= 9)
 28040         {
 28041           tenths = remainder / 100;
 28042           if (remainder % 100 >= 50)
 28043             {
 28044               if (tenths < 9)
 28045                 tenths++;
 28046               else
 28047                 {
 28048                   quotient++;
 28049                   if (quotient == 10)
 28050                     tenths = -1;
 28051                   else
 28052                     tenths = 0;
 28053                 }
 28054             }
 28055         }
 28056       else
 28057         if (remainder >= 500)
 28058           {
 28059             if (quotient < 999)
 28060               quotient++;
 28061             else
 28062               {
 28063                 quotient = 1;
 28064                 exponent++;
 28065                 tenths = 0;
 28066               }
 28067           }
 28068     }
 28069 
 28070   /* Calculate the LENGTH of QUOTIENT.TENTHS as a string. */
 28071   if (tenths == -1 && quotient <= 99)
 28072     if (quotient <= 9)
 28073       length = 1;
 28074     else
 28075       length = 2;
 28076   else
 28077     length = 3;
 28078   p = psuffix = buf + max (width, length);
 28079 
 28080   /* Print EXPONENT. */
 28081   *psuffix++ = power_letter[exponent];
 28082   *psuffix = '\0';
 28083 
 28084   /* Print TENTHS. */
 28085   if (tenths >= 0)
 28086     {
 28087       *--p = '0' + tenths;
 28088       *--p = '.';
 28089     }
 28090 
 28091   /* Print QUOTIENT. */
 28092   do
 28093     {
 28094       int digit = quotient % 10;
 28095       *--p =  '0' + digit;
 28096     }
 28097   while ((quotient /= 10) != 0);
 28098 
 28099   /* Print leading spaces. */
 28100   while (buf < p)
 28101     *--p = ' ';
 28102 }
 28103 
 28104 /* Set a mnemonic character for coding_system (Lisp symbol) in BUF.
 28105    If EOL_FLAG, set also a mnemonic character for end-of-line
 28106    type of CODING_SYSTEM.  Return updated pointer into BUF.  */
 28107 
 28108 static unsigned char invalid_eol_type[] = "(*invalid*)";
 28109 
 28110 static char *
 28111 decode_mode_spec_coding (Lisp_Object coding_system, char *buf, bool eol_flag)
 28112 {
 28113   Lisp_Object val;
 28114   bool multibyte = !NILP (BVAR (current_buffer, enable_multibyte_characters));
 28115   const unsigned char *eol_str;
 28116   int eol_str_len;
 28117   /* The EOL conversion we are using.  */
 28118   Lisp_Object eoltype;
 28119 
 28120   val = CODING_SYSTEM_SPEC (coding_system);
 28121   eoltype = Qnil;
 28122 
 28123   if (!VECTORP (val))           /* Not yet decided.  */
 28124     {
 28125       *buf++ = multibyte ? '-' : ' ';
 28126       if (eol_flag)
 28127         eoltype = eol_mnemonic_undecided;
 28128       /* Don't mention EOL conversion if it isn't decided.  */
 28129     }
 28130   else
 28131     {
 28132       Lisp_Object attrs;
 28133       Lisp_Object eolvalue;
 28134 
 28135       attrs = AREF (val, 0);
 28136       eolvalue = AREF (val, 2);
 28137 
 28138       if (multibyte)
 28139         buf += CHAR_STRING (XFIXNAT (CODING_ATTR_MNEMONIC (attrs)),
 28140                             (unsigned char *) buf);
 28141       else
 28142         *buf++ = ' ';
 28143 
 28144       if (eol_flag)
 28145         {
 28146           /* The EOL conversion that is normal on this system.  */
 28147 
 28148           if (NILP (eolvalue))  /* Not yet decided.  */
 28149             eoltype = eol_mnemonic_undecided;
 28150           else if (VECTORP (eolvalue)) /* Not yet decided.  */
 28151             eoltype = eol_mnemonic_undecided;
 28152           else                  /* eolvalue is Qunix, Qdos, or Qmac.  */
 28153             eoltype = (EQ (eolvalue, Qunix)
 28154                        ? eol_mnemonic_unix
 28155                        : EQ (eolvalue, Qdos)
 28156                        ? eol_mnemonic_dos : eol_mnemonic_mac);
 28157         }
 28158     }
 28159 
 28160   if (eol_flag)
 28161     {
 28162       /* Mention the EOL conversion if it is not the usual one.  */
 28163       if (STRINGP (eoltype))
 28164         {
 28165           eol_str = SDATA (eoltype);
 28166           eol_str_len = SBYTES (eoltype);
 28167         }
 28168       else if (CHARACTERP (eoltype))
 28169         {
 28170           int c = XFIXNAT (eoltype);
 28171           return buf + CHAR_STRING (c, (unsigned char *) buf);
 28172         }
 28173       else
 28174         {
 28175           eol_str = invalid_eol_type;
 28176           eol_str_len = sizeof (invalid_eol_type) - 1;
 28177         }
 28178       memcpy (buf, eol_str, eol_str_len);
 28179       buf += eol_str_len;
 28180     }
 28181 
 28182   return buf;
 28183 }
 28184 
 28185 /* Return the approximate percentage N is of D (rounding upward), or 99,
 28186    whichever is less.  Assume 0 < D and 0 <= N <= D * INT_MAX / 100.  */
 28187 
 28188 static int
 28189 percent99 (ptrdiff_t n, ptrdiff_t d)
 28190 {
 28191   int percent = (d - 1 + 100.0 * n) / d;
 28192   return min (percent, 99);
 28193 }
 28194 
 28195 /* Return a string for the output of a mode line %-spec for window W,
 28196    generated by character C.  FIELD_WIDTH > 0 means pad the string
 28197    returned with spaces to that value.  Set *STRING to be a Lisp
 28198    string if the resulting string is taken from that Lisp string;
 28199    otherwise, set *STRING to Qnil.
 28200 
 28201    Note we operate on the current buffer for most purposes.  */
 28202 
 28203 static char lots_of_dashes[] = "--------------------------------------------------------------------------------------------------------------------------------------------";
 28204 
 28205 static const char *
 28206 decode_mode_spec (struct window *w, register int c, int field_width,
 28207                   Lisp_Object *string)
 28208 {
 28209   Lisp_Object obj;
 28210   struct frame *f = XFRAME (WINDOW_FRAME (w));
 28211   char *decode_mode_spec_buf = f->decode_mode_spec_buffer;
 28212   /* We are going to use f->decode_mode_spec_buffer as the buffer to
 28213      produce strings from numerical values, so limit preposterously
 28214      large values of FIELD_WIDTH to avoid overrunning the buffer's
 28215      end.  The size of the buffer is enough for FRAME_MESSAGE_BUF_SIZE
 28216      bytes plus the terminating null.  */
 28217   int width = min (field_width, FRAME_MESSAGE_BUF_SIZE (f));
 28218   struct buffer *b = current_buffer;
 28219 
 28220   obj = Qnil;
 28221   *string = Qnil;
 28222 
 28223   switch (c)
 28224     {
 28225     case '*':
 28226       if (!NILP (BVAR (b, read_only)))
 28227         return "%";
 28228       if (BUF_MODIFF (b) > BUF_SAVE_MODIFF (b))
 28229         return "*";
 28230       return "-";
 28231 
 28232     case '+':
 28233       /* This differs from %* only for a modified read-only buffer.  */
 28234       if (BUF_MODIFF (b) > BUF_SAVE_MODIFF (b))
 28235         return "*";
 28236       if (!NILP (BVAR (b, read_only)))
 28237         return "%";
 28238       return "-";
 28239 
 28240     case '&':
 28241       /* This differs from %* in ignoring read-only-ness.  */
 28242       if (BUF_MODIFF (b) > BUF_SAVE_MODIFF (b))
 28243         return "*";
 28244       return "-";
 28245 
 28246     case '%':
 28247       return "%";
 28248 
 28249     case '[':
 28250       {
 28251         int i;
 28252         char *p;
 28253 
 28254         if (command_loop_level > 5)
 28255           return "[[[... ";
 28256         p = decode_mode_spec_buf;
 28257         for (i = 0; i < command_loop_level; i++)
 28258           *p++ = '[';
 28259         *p = 0;
 28260         return decode_mode_spec_buf;
 28261       }
 28262 
 28263     case ']':
 28264       {
 28265         int i;
 28266         char *p;
 28267 
 28268         if (command_loop_level > 5)
 28269           return " ...]]]";
 28270         p = decode_mode_spec_buf;
 28271         for (i = 0; i < command_loop_level; i++)
 28272           *p++ = ']';
 28273         *p = 0;
 28274         return decode_mode_spec_buf;
 28275       }
 28276 
 28277     case '-':
 28278       {
 28279         register int i;
 28280 
 28281         /* Let lots_of_dashes be a string of infinite length.  */
 28282         if (mode_line_target == MODE_LINE_NOPROP
 28283             || mode_line_target == MODE_LINE_STRING)
 28284           return "--";
 28285         if (field_width <= 0
 28286             || field_width > sizeof (lots_of_dashes))
 28287           {
 28288             for (i = 0; i < FRAME_MESSAGE_BUF_SIZE (f) - 1; ++i)
 28289               decode_mode_spec_buf[i] = '-';
 28290             decode_mode_spec_buf[i] = '\0';
 28291             return decode_mode_spec_buf;
 28292           }
 28293         else
 28294           return lots_of_dashes;
 28295       }
 28296 
 28297     case 'b':
 28298       obj = BVAR (b, name);
 28299       break;
 28300 
 28301     case 'c':
 28302     case 'C':
 28303       /* %c, %C, and %l are ignored in `frame-title-format'.
 28304          (In redisplay_internal, the frame title is drawn _before_ the
 28305          windows are updated, so the stuff which depends on actual
 28306          window contents (such as %l) may fail to render properly, or
 28307          even crash emacs.)  */
 28308       if (mode_line_target == MODE_LINE_TITLE)
 28309         return "";
 28310       else
 28311         {
 28312           ptrdiff_t col = current_column ();
 28313           int disp_col = (c == 'C') ? col + 1 : col;
 28314           w->column_number_displayed = col;
 28315           pint2str (decode_mode_spec_buf, width, disp_col);
 28316           return decode_mode_spec_buf;
 28317         }
 28318 
 28319     case 'e':
 28320 #if !defined SYSTEM_MALLOC && !defined HYBRID_MALLOC
 28321       {
 28322         if (NILP (Vmemory_full))
 28323           return "";
 28324         else
 28325           return "!MEM FULL! ";
 28326       }
 28327 #else
 28328       return "";
 28329 #endif
 28330 
 28331     case 'F':
 28332       /* %F displays the frame name.  */
 28333       if (!NILP (f->title))
 28334         return SSDATA (f->title);
 28335       if (f->explicit_name || ! FRAME_WINDOW_P (f))
 28336         return SSDATA (f->name);
 28337       return "Emacs";
 28338 
 28339     case 'f':
 28340       obj = BVAR (b, filename);
 28341       break;
 28342 
 28343     case 'i':
 28344       {
 28345         ptrdiff_t size = ZV - BEGV;
 28346         pint2str (decode_mode_spec_buf, width, size);
 28347         return decode_mode_spec_buf;
 28348       }
 28349 
 28350     case 'I':
 28351       {
 28352         ptrdiff_t size = ZV - BEGV;
 28353         pint2hrstr (decode_mode_spec_buf, width, size);
 28354         return decode_mode_spec_buf;
 28355       }
 28356 
 28357     case 'l':
 28358       {
 28359         ptrdiff_t startpos, startpos_byte, line, linepos, linepos_byte;
 28360         ptrdiff_t topline, nlines, height;
 28361         ptrdiff_t junk;
 28362 
 28363         /* %c, %C, and %l are ignored in `frame-title-format'.  */
 28364         if (mode_line_target == MODE_LINE_TITLE)
 28365           return "";
 28366 
 28367         startpos = marker_position (w->start);
 28368         startpos_byte = marker_byte_position (w->start);
 28369         height = WINDOW_TOTAL_LINES (w);
 28370         /* We cannot cope with w->start being outside of the
 28371            accessible portion of the buffer; in particular,
 28372            display_count_lines call below might infloop if called with
 28373            startpos_byte outside of the [BEGV_BYTE..ZV_BYTE] region.
 28374            Such w->start means we were called in some "creative" way
 28375            when the buffer's restriction was changed, but the window
 28376            wasn't yet redisplayed after that.  If that happens, we
 28377            need to determine a new base line.  */
 28378         if (!(BUF_BEGV_BYTE (b) <= startpos_byte
 28379               && startpos_byte <= BUF_ZV_BYTE (b)))
 28380           {
 28381             startpos = BUF_BEGV (b);
 28382             startpos_byte = BUF_BEGV_BYTE (b);
 28383             w->base_line_pos = 0;
 28384             w->base_line_number = 0;
 28385           }
 28386 
 28387         /* If we decided that this buffer isn't suitable for line numbers,
 28388            don't forget that too fast.  */
 28389         if (w->base_line_pos == -1)
 28390           goto no_value;
 28391 
 28392         /* If the buffer is very big, don't waste time.  */
 28393         if (FIXNUMP (Vline_number_display_limit)
 28394             && BUF_ZV (b) - BUF_BEGV (b) > XFIXNUM (Vline_number_display_limit))
 28395           {
 28396             w->base_line_pos = 0;
 28397             w->base_line_number = 0;
 28398             goto no_value;
 28399           }
 28400 
 28401         if (w->base_line_number > 0
 28402             && w->base_line_pos > 0
 28403             && w->base_line_pos <= startpos)
 28404           {
 28405             line = w->base_line_number;
 28406             linepos = w->base_line_pos;
 28407             linepos_byte = buf_charpos_to_bytepos (b, linepos);
 28408           }
 28409         else
 28410           {
 28411             line = 1;
 28412             linepos = BUF_BEGV (b);
 28413             linepos_byte = BUF_BEGV_BYTE (b);
 28414           }
 28415 
 28416         /* Count lines from base line to window start position.  */
 28417         nlines = display_count_lines (linepos_byte,
 28418                                       startpos_byte,
 28419                                       startpos, &junk);
 28420 
 28421         topline = nlines + line;
 28422 
 28423         /* Determine a new base line, if the old one is too close
 28424            or too far away, or if we did not have one.
 28425            "Too close" means it's plausible a scroll-down would
 28426            go back past it.  */
 28427         if (startpos == BUF_BEGV (b))
 28428           {
 28429             w->base_line_number = topline;
 28430             w->base_line_pos = BUF_BEGV (b);
 28431           }
 28432         else if (nlines < height + 25 || nlines > height * 3 + 50
 28433                  || linepos == BUF_BEGV (b))
 28434           {
 28435             ptrdiff_t limit = BUF_BEGV (b);
 28436             ptrdiff_t limit_byte = BUF_BEGV_BYTE (b);
 28437             ptrdiff_t position;
 28438             ptrdiff_t distance
 28439               = (line_number_display_limit_width < 0 ? 0
 28440                  : ckd_mul (&distance, line_number_display_limit_width,
 28441                             height * 2 + 30)
 28442                  ? PTRDIFF_MAX : distance);
 28443 
 28444             if (startpos - distance > limit)
 28445               {
 28446                 limit = startpos - distance;
 28447                 limit_byte = CHAR_TO_BYTE (limit);
 28448               }
 28449 
 28450             nlines = display_count_lines (startpos_byte,
 28451                                           limit_byte,
 28452                                           - (height * 2 + 30),
 28453                                           &position);
 28454             /* If we couldn't find the lines we wanted within
 28455                line_number_display_limit_width chars per line,
 28456                give up on line numbers for this window.  */
 28457             if (position == limit_byte && limit == startpos - distance)
 28458               {
 28459                 w->base_line_pos = -1;
 28460                 w->base_line_number = 0;
 28461                 goto no_value;
 28462               }
 28463 
 28464             w->base_line_number = topline - nlines;
 28465             w->base_line_pos = BYTE_TO_CHAR (position);
 28466           }
 28467 
 28468         /* Now count lines from the start pos to point.  */
 28469         nlines = display_count_lines (startpos_byte,
 28470                                       PT_BYTE, PT, &junk);
 28471 
 28472         /* Record that we did display the line number.  */
 28473         line_number_displayed = true;
 28474 
 28475         /* Make the string to show.  */
 28476         pint2str (decode_mode_spec_buf, width, topline + nlines);
 28477         return decode_mode_spec_buf;
 28478     no_value:
 28479         {
 28480           char *p = decode_mode_spec_buf;
 28481           int pad = width - 2;
 28482           while (pad-- > 0)
 28483             *p++ = ' ';
 28484           *p++ = '?';
 28485           *p++ = '?';
 28486           *p = '\0';
 28487           return decode_mode_spec_buf;
 28488         }
 28489       }
 28490       break;
 28491 
 28492     case 'm':
 28493       obj = BVAR (b, mode_name);
 28494       break;
 28495 
 28496     case 'n':
 28497       if (BUF_BEGV (b) > BUF_BEG (b) || BUF_ZV (b) < BUF_Z (b))
 28498         return " Narrow";
 28499       break;
 28500 
 28501       /* Display the "degree of travel" of the window through the buffer.  */
 28502     case 'o':
 28503       {
 28504         ptrdiff_t toppos = marker_position (w->start);
 28505         ptrdiff_t botpos = BUF_Z (b) - w->window_end_pos;
 28506         ptrdiff_t begv = BUF_BEGV (b);
 28507         ptrdiff_t zv = BUF_ZV (b);
 28508 
 28509         if (zv <= botpos)
 28510           return toppos <= begv ? "All" : "Bottom";
 28511         else if (toppos <= begv)
 28512           return "Top";
 28513         else
 28514           {
 28515           sprintf (decode_mode_spec_buf, "%2d%%",
 28516                    percent99 (toppos - begv, (toppos - begv) + (zv - botpos)));
 28517           return decode_mode_spec_buf;
 28518           }
 28519       }
 28520 
 28521       /* Display percentage of buffer above the top of the screen.  */
 28522     case 'p':
 28523       {
 28524         ptrdiff_t pos = marker_position (w->start);
 28525         ptrdiff_t begv = BUF_BEGV (b);
 28526         ptrdiff_t zv = BUF_ZV (b);
 28527 
 28528         if (w->window_end_pos <= BUF_Z (b) - zv)
 28529           return pos <= begv ? "All" : "Bottom";
 28530         else if (pos <= begv)
 28531           return "Top";
 28532         else
 28533           {
 28534             sprintf (decode_mode_spec_buf, "%2d%%",
 28535                      percent99 (pos - begv, zv - begv));
 28536             return decode_mode_spec_buf;
 28537           }
 28538       }
 28539 
 28540       /* Display percentage of size above the bottom of the screen.  */
 28541     case 'P':
 28542       {
 28543         ptrdiff_t toppos = marker_position (w->start);
 28544         ptrdiff_t botpos = BUF_Z (b) - w->window_end_pos;
 28545         ptrdiff_t begv = BUF_BEGV (b);
 28546         ptrdiff_t zv = BUF_ZV (b);
 28547 
 28548         if (zv <= botpos)
 28549           return toppos <= begv ? "All" : "Bottom";
 28550         else
 28551           {
 28552             sprintf (decode_mode_spec_buf,
 28553                      &"Top%2d%%"[begv < toppos ? sizeof "Top" - 1 : 0],
 28554                      percent99 (botpos - begv, zv - begv));
 28555             return decode_mode_spec_buf;
 28556           }
 28557       }
 28558 
 28559       /* Display percentage offsets of top and bottom of the window,
 28560          using "All" (but not "Top" or "Bottom") where appropriate.  */
 28561     case 'q':
 28562       {
 28563         ptrdiff_t toppos = marker_position (w->start);
 28564         ptrdiff_t botpos = BUF_Z (b) - w->window_end_pos;
 28565         ptrdiff_t begv = BUF_BEGV (b);
 28566         ptrdiff_t zv = BUF_ZV (b);
 28567         int top_perc, bot_perc;
 28568 
 28569         if ((toppos <= begv) && (zv <= botpos))
 28570           return "All   ";
 28571 
 28572         top_perc = toppos <= begv ? 0 : percent99 (toppos - begv, zv - begv);
 28573         bot_perc = zv <= botpos ? 100 : percent99 (botpos - begv, zv - begv);
 28574 
 28575         if (top_perc == bot_perc)
 28576           sprintf (decode_mode_spec_buf, "%d%%", top_perc);
 28577         else
 28578           sprintf (decode_mode_spec_buf, "%d-%d%%", top_perc, bot_perc);
 28579 
 28580         return decode_mode_spec_buf;
 28581       }
 28582 
 28583     case 's':
 28584       /* status of process */
 28585       obj = Fget_buffer_process (Fcurrent_buffer ());
 28586       if (NILP (obj))
 28587         return "no process";
 28588 #ifndef MSDOS
 28589       obj = Fsymbol_name (Fprocess_status (obj));
 28590 #endif
 28591       break;
 28592 
 28593     case '@':
 28594       {
 28595         specpdl_ref count = inhibit_garbage_collection ();
 28596         Lisp_Object curdir = BVAR (current_buffer, directory);
 28597         Lisp_Object val = Qnil;
 28598 
 28599         if (STRINGP (curdir))
 28600           val = safe_call1 (intern ("file-remote-p"), curdir);
 28601 
 28602         val = unbind_to (count, val);
 28603 
 28604         if (NILP (val))
 28605           return "-";
 28606         else
 28607           return "@";
 28608       }
 28609 
 28610     case 'z':
 28611       /* coding-system (not including end-of-line format) */
 28612     case 'Z':
 28613       /* coding-system (including end-of-line type) */
 28614       {
 28615         bool eol_flag = (c == 'Z');
 28616         char *p = decode_mode_spec_buf;
 28617 
 28618         if (! FRAME_WINDOW_P (f))
 28619           {
 28620             /* No need to mention EOL here--the terminal never needs
 28621                to do EOL conversion.  */
 28622             p = decode_mode_spec_coding (CODING_ID_NAME
 28623                                          (FRAME_KEYBOARD_CODING (f)->id),
 28624                                          p, false);
 28625             p = decode_mode_spec_coding (CODING_ID_NAME
 28626                                          (FRAME_TERMINAL_CODING (f)->id),
 28627                                          p, false);
 28628           }
 28629         p = decode_mode_spec_coding (BVAR (b, buffer_file_coding_system),
 28630                                      p, eol_flag);
 28631 
 28632 #if false /* This proves to be annoying; I think we can do without. -- rms.  */
 28633 #ifdef subprocesses
 28634         obj = Fget_buffer_process (Fcurrent_buffer ());
 28635         if (PROCESSP (obj))
 28636           {
 28637             p = decode_mode_spec_coding
 28638               (XPROCESS (obj)->decode_coding_system, p, eol_flag);
 28639             p = decode_mode_spec_coding
 28640               (XPROCESS (obj)->encode_coding_system, p, eol_flag);
 28641           }
 28642 #endif /* subprocesses */
 28643 #endif /* false */
 28644         *p = 0;
 28645         return decode_mode_spec_buf;
 28646       }
 28647     }
 28648 
 28649   if (STRINGP (obj))
 28650     {
 28651       *string = obj;
 28652       return SSDATA (obj);
 28653     }
 28654   else
 28655     return "";
 28656 }
 28657 
 28658 /* Return the number of lines between start_byte and end_byte in the
 28659    current buffer. */
 28660 
 28661 ptrdiff_t
 28662 count_lines (ptrdiff_t start_byte, ptrdiff_t end_byte)
 28663 {
 28664   ptrdiff_t ignored;
 28665   return display_count_lines (start_byte, end_byte, ZV, &ignored);
 28666 }
 28667 
 28668 /* Count up to COUNT lines starting from START_BYTE.  COUNT negative
 28669    means count lines back from START_BYTE.  But don't go beyond
 28670    LIMIT_BYTE.  Return the number of lines thus found (always
 28671    nonnegative).
 28672 
 28673    Set *BYTE_POS_PTR to the byte position where we stopped.  This is
 28674    either the position COUNT lines after/before START_BYTE, if we
 28675    found COUNT lines, or LIMIT_BYTE if we hit the limit before finding
 28676    COUNT lines.  */
 28677 
 28678 static ptrdiff_t
 28679 display_count_lines (ptrdiff_t start_byte,
 28680                      ptrdiff_t limit_byte, ptrdiff_t count,
 28681                      ptrdiff_t *byte_pos_ptr)
 28682 {
 28683   register unsigned char *cursor;
 28684   unsigned char *base;
 28685 
 28686   register ptrdiff_t ceiling;
 28687   register unsigned char *ceiling_addr;
 28688   ptrdiff_t orig_count = count;
 28689 
 28690   /* If we are not in selective display mode,
 28691      check only for newlines.  */
 28692   bool selective_display
 28693     = (!NILP (BVAR (current_buffer, selective_display))
 28694        && !FIXNUMP (BVAR (current_buffer, selective_display)));
 28695 
 28696   if (count > 0)
 28697     {
 28698       while (start_byte < limit_byte)
 28699         {
 28700           ceiling =  BUFFER_CEILING_OF (start_byte);
 28701           ceiling = min (limit_byte - 1, ceiling);
 28702           ceiling_addr = BYTE_POS_ADDR (ceiling) + 1;
 28703           base = (cursor = BYTE_POS_ADDR (start_byte));
 28704 
 28705           do
 28706             {
 28707               if (selective_display)
 28708                 {
 28709                   while (*cursor != '\n' && *cursor != 015
 28710                          && ++cursor != ceiling_addr)
 28711                     continue;
 28712                   if (cursor == ceiling_addr)
 28713                     break;
 28714                 }
 28715               else
 28716                 {
 28717                   cursor = memchr (cursor, '\n', ceiling_addr - cursor);
 28718                   if (! cursor)
 28719                     break;
 28720                 }
 28721 
 28722               cursor++;
 28723 
 28724               if (--count == 0)
 28725                 {
 28726                   start_byte += cursor - base;
 28727                   *byte_pos_ptr = start_byte;
 28728                   return orig_count;
 28729                 }
 28730             }
 28731           while (cursor < ceiling_addr);
 28732 
 28733           start_byte += ceiling_addr - base;
 28734         }
 28735     }
 28736   else
 28737     {
 28738       while (start_byte > limit_byte)
 28739         {
 28740           ceiling = BUFFER_FLOOR_OF (start_byte - 1);
 28741           ceiling = max (limit_byte, ceiling);
 28742           ceiling_addr = BYTE_POS_ADDR (ceiling);
 28743           base = (cursor = BYTE_POS_ADDR (start_byte - 1) + 1);
 28744           while (true)
 28745             {
 28746               if (selective_display)
 28747                 {
 28748                   while (--cursor >= ceiling_addr
 28749                          && *cursor != '\n' && *cursor != 015)
 28750                     continue;
 28751                   if (cursor < ceiling_addr)
 28752                     break;
 28753                 }
 28754               else
 28755                 {
 28756                   cursor = memrchr (ceiling_addr, '\n', cursor - ceiling_addr);
 28757                   if (! cursor)
 28758                     break;
 28759                 }
 28760 
 28761               if (++count == 0)
 28762                 {
 28763                   start_byte += cursor - base + 1;
 28764                   *byte_pos_ptr = start_byte;
 28765                   /* When scanning backwards, we should
 28766                      not count the newline posterior to which we stop.  */
 28767                   return - orig_count - 1;
 28768                 }
 28769             }
 28770           start_byte += ceiling_addr - base;
 28771         }
 28772     }
 28773 
 28774   *byte_pos_ptr = limit_byte;
 28775 
 28776   if (count < 0)
 28777     return - orig_count + count;
 28778   return orig_count - count;
 28779 
 28780 }
 28781 
 28782 
 28783 
 28784 /***********************************************************************
 28785                          Displaying strings
 28786  ***********************************************************************/
 28787 
 28788 /* Display a NUL-terminated string, starting with index START.
 28789 
 28790    If STRING is non-null, display that C string.  Otherwise, the Lisp
 28791    string LISP_STRING is displayed.  There's a case that STRING is
 28792    non-null and LISP_STRING is not nil.  It means STRING is a string
 28793    data of LISP_STRING.  In that case, we display LISP_STRING while
 28794    ignoring its text properties.
 28795 
 28796    If FACE_STRING is not nil, FACE_STRING_POS is a position in
 28797    FACE_STRING.  Display STRING or LISP_STRING with the face at
 28798    FACE_STRING_POS in FACE_STRING:
 28799 
 28800    Display the string in the environment given by IT, but use the
 28801    standard display table, temporarily.
 28802 
 28803    FIELD_WIDTH is the minimum number of output glyphs to produce.
 28804    If STRING has fewer characters than FIELD_WIDTH, pad to the right
 28805    with spaces.  If STRING has more characters, more than FIELD_WIDTH
 28806    glyphs will be produced.  FIELD_WIDTH <= 0 means don't pad.
 28807 
 28808    PRECISION is the maximum number of characters to output from
 28809    STRING.  PRECISION < 0  means don't truncate the string.
 28810 
 28811    This is roughly equivalent to printf format specifiers:
 28812 
 28813    FIELD_WIDTH  PRECISION       PRINTF
 28814    ----------------------------------------
 28815    -1           -1              %s
 28816    -1           10              %.10s
 28817    10           -1              %10s
 28818    20           10              %20.10s
 28819 
 28820    MULTIBYTE zero means do not display multibyte chars, > 0 means do
 28821    display them, and < 0 means obey the current buffer's value of
 28822    enable_multibyte_characters.
 28823 
 28824    Value is the number of columns displayed.  */
 28825 
 28826 static int
 28827 display_string (const char *string, Lisp_Object lisp_string, Lisp_Object face_string,
 28828                 ptrdiff_t face_string_pos, ptrdiff_t start, struct it *it,
 28829                 int field_width, int precision, int max_x, int multibyte)
 28830 {
 28831   int hpos_at_start = it->hpos;
 28832   int saved_face_id = it->face_id;
 28833   struct glyph_row *row = it->glyph_row;
 28834   ptrdiff_t it_charpos;
 28835 
 28836   /* Initialize the iterator IT for iteration over STRING beginning
 28837      with index START.  */
 28838   reseat_to_string (it, NILP (lisp_string) ? string : NULL, lisp_string,
 28839                     start, precision, field_width, multibyte);
 28840 
 28841   if (string && STRINGP (lisp_string))
 28842     /* LISP_STRING is the one returned by decode_mode_spec.  We should
 28843        ignore its text properties.  */
 28844     it->stop_charpos = it->end_charpos;
 28845 
 28846   /* If displaying STRING, set up the face of the iterator from
 28847      FACE_STRING, if that's given.  */
 28848   if (STRINGP (face_string))
 28849     {
 28850       ptrdiff_t endptr;
 28851       struct face *face;
 28852 
 28853       it->face_id
 28854         = face_at_string_position (it->w, face_string, face_string_pos,
 28855                                    0, &endptr, it->base_face_id, false, 0);
 28856       face = FACE_FROM_ID (it->f, it->face_id);
 28857       it->face_box_p = face->box != FACE_NO_BOX;
 28858 
 28859       /* If we have a display spec, but there's no Lisp string being
 28860          displayed, then check whether we've got one from the
 28861          :propertize being passed in and use that.  */
 28862       if (NILP (lisp_string))
 28863         {
 28864           Lisp_Object display = Fget_text_property (make_fixnum (0), Qdisplay,
 28865                                                     face_string);
 28866           if (!NILP (display))
 28867             {
 28868               Lisp_Object min_width = plist_get (display, Qmin_width);
 28869               if (!NILP (min_width))
 28870                 display_min_width (it, 0, face_string, min_width);
 28871             }
 28872         }
 28873     }
 28874 
 28875   /* Set max_x to the maximum allowed X position.  Don't let it go
 28876      beyond the right edge of the window.  */
 28877   if (max_x <= 0)
 28878     max_x = it->last_visible_x;
 28879   else
 28880     max_x = min (max_x, it->last_visible_x);
 28881 
 28882   /* Skip over display elements that are not visible because IT->w is
 28883      hscrolled.  */
 28884   if (it->current_x < it->first_visible_x)
 28885     move_it_in_display_line_to (it, 100000, it->first_visible_x,
 28886                                 MOVE_TO_POS | MOVE_TO_X);
 28887 
 28888   row->ascent = it->max_ascent;
 28889   row->height = it->max_ascent + it->max_descent;
 28890   row->phys_ascent = it->max_phys_ascent;
 28891   row->phys_height = it->max_phys_ascent + it->max_phys_descent;
 28892   row->extra_line_spacing = it->max_extra_line_spacing;
 28893 
 28894   if (STRINGP (it->string))
 28895     it_charpos = IT_STRING_CHARPOS (*it);
 28896   else
 28897     it_charpos = IT_CHARPOS (*it);
 28898 
 28899   /* This condition is for the case that we are called with current_x
 28900      past last_visible_x.  */
 28901   while (it->current_x < max_x)
 28902     {
 28903       int x_before, x, n_glyphs_before, i, nglyphs;
 28904 
 28905       /* Get the next display element.  */
 28906       if (!get_next_display_element (it))
 28907         break;
 28908 
 28909       /* Produce glyphs.  */
 28910       x_before = it->current_x;
 28911       n_glyphs_before = row->used[TEXT_AREA];
 28912       PRODUCE_GLYPHS (it);
 28913 
 28914       nglyphs = row->used[TEXT_AREA] - n_glyphs_before;
 28915       i = 0;
 28916       x = x_before;
 28917       while (i < nglyphs)
 28918         {
 28919           struct glyph *glyph = row->glyphs[TEXT_AREA] + n_glyphs_before + i;
 28920 
 28921           if (it->line_wrap != TRUNCATE
 28922               && x + glyph->pixel_width > max_x)
 28923             {
 28924               /* End of continued line or max_x reached.  */
 28925               if (CHAR_GLYPH_PADDING_P (*glyph))
 28926                 {
 28927                   /* A wide character is unbreakable.  */
 28928                   if (row->reversed_p)
 28929                     unproduce_glyphs (it, row->used[TEXT_AREA]
 28930                                       - n_glyphs_before);
 28931                   row->used[TEXT_AREA] = n_glyphs_before;
 28932                   it->current_x = x_before;
 28933                 }
 28934               else
 28935                 {
 28936                   if (row->reversed_p)
 28937                     unproduce_glyphs (it, row->used[TEXT_AREA]
 28938                                       - (n_glyphs_before + i));
 28939                   row->used[TEXT_AREA] = n_glyphs_before + i;
 28940                   it->current_x = x;
 28941                 }
 28942               break;
 28943             }
 28944           else if (x + glyph->pixel_width >= it->first_visible_x)
 28945             {
 28946               /* Glyph is at least partially visible.  */
 28947               ++it->hpos;
 28948               if (x < it->first_visible_x)
 28949                 row->x = x - it->first_visible_x;
 28950             }
 28951           else
 28952             {
 28953               /* Glyph is off the left margin of the display area.
 28954                  Should not happen.  */
 28955               emacs_abort ();
 28956             }
 28957 
 28958           row->ascent = max (row->ascent, it->max_ascent);
 28959           row->height = max (row->height, it->max_ascent + it->max_descent);
 28960           row->phys_ascent = max (row->phys_ascent, it->max_phys_ascent);
 28961           row->phys_height = max (row->phys_height,
 28962                                   it->max_phys_ascent + it->max_phys_descent);
 28963           row->extra_line_spacing = max (row->extra_line_spacing,
 28964                                          it->max_extra_line_spacing);
 28965           x += glyph->pixel_width;
 28966           ++i;
 28967         }
 28968 
 28969       /* Stop if max_x reached.  */
 28970       if (i < nglyphs)
 28971         break;
 28972 
 28973       /* Stop at line ends.  */
 28974       if (ITERATOR_AT_END_OF_LINE_P (it))
 28975         {
 28976           it->continuation_lines_width = 0;
 28977           break;
 28978         }
 28979 
 28980       set_iterator_to_next (it, true);
 28981       if (STRINGP (it->string))
 28982         it_charpos = IT_STRING_CHARPOS (*it);
 28983       else
 28984         it_charpos = IT_CHARPOS (*it);
 28985 
 28986       /* Stop if truncating at the right edge.  */
 28987       if (it->line_wrap == TRUNCATE
 28988           && it->current_x >= it->last_visible_x)
 28989         {
 28990           /* Add truncation mark, but don't do it if the line is
 28991              truncated at a padding space.  */
 28992           /* Need to do the below for the last string character as
 28993              well, since it could be a double-width character, in
 28994              which case the previous character ends before
 28995              last_visible_x.  Thus, comparison with <=, not <.  */
 28996           if (it_charpos <= it->string_nchars)
 28997             {
 28998               if (!FRAME_WINDOW_P (it->f))
 28999                 {
 29000                   int ii, n;
 29001 
 29002                   if (it->current_x > it->last_visible_x)
 29003                     {
 29004                       /* This flag is true if we are displaying mode
 29005                          line, false for header-line or tab-line.  */
 29006                       bool mode_line_p = false;
 29007 
 29008                       /* ROW->mode_line_p is true if we display mode
 29009                          line or header-line or tab-line.  */
 29010                       if (row->mode_line_p)
 29011                         {
 29012                           struct window *w = it->w;
 29013                           if (row == MATRIX_MODE_LINE_ROW (w->desired_matrix))
 29014                             mode_line_p = true;
 29015                         }
 29016                       if (!row->reversed_p)
 29017                         {
 29018                           for (ii = row->used[TEXT_AREA] - 1; ii > 0; --ii)
 29019                             if (!CHAR_GLYPH_PADDING_P (row->glyphs[TEXT_AREA][ii]))
 29020                               break;
 29021                         }
 29022                       else
 29023                         {
 29024                           for (ii = 0; ii < row->used[TEXT_AREA]; ii++)
 29025                             if (!CHAR_GLYPH_PADDING_P (row->glyphs[TEXT_AREA][ii]))
 29026                               break;
 29027                           unproduce_glyphs (it, ii + 1);
 29028                           ii = row->used[TEXT_AREA] - (ii + 1);
 29029                         }
 29030                       for (n = row->used[TEXT_AREA]; ii < n; ++ii)
 29031                         {
 29032                           row->used[TEXT_AREA] = ii;
 29033                           if (row->mode_line_p)
 29034                             pad_mode_line (it, mode_line_p);
 29035                           else
 29036                             produce_special_glyphs (it, IT_TRUNCATION);
 29037                         }
 29038                     }
 29039                   produce_special_glyphs (it, IT_TRUNCATION);
 29040                 }
 29041               row->truncated_on_right_p = true;
 29042             }
 29043           break;
 29044         }
 29045     }
 29046 
 29047   /* Maybe insert a truncation at the left.  */
 29048   if (it->first_visible_x
 29049       && it_charpos > 0)
 29050     {
 29051       if (!FRAME_WINDOW_P (it->f)
 29052           || (row->reversed_p
 29053               ? WINDOW_RIGHT_FRINGE_WIDTH (it->w)
 29054               : WINDOW_LEFT_FRINGE_WIDTH (it->w)) == 0)
 29055         insert_left_trunc_glyphs (it);
 29056       row->truncated_on_left_p = true;
 29057     }
 29058 
 29059   it->face_id = saved_face_id;
 29060 
 29061   /* Value is number of columns displayed.  */
 29062   return it->hpos - hpos_at_start;
 29063 }
 29064 
 29065 
 29066 
 29067 /* This is like a combination of memq and assq.  Return 1/2 if PROPVAL
 29068    appears as an element of LIST or as the car of an element of LIST.
 29069    If PROPVAL is a list, compare each element against LIST in that
 29070    way, and return 1/2 if any element of PROPVAL is found in LIST.
 29071    Otherwise return 0.  This function cannot quit.
 29072    The return value is 2 if the text is invisible but with an ellipsis
 29073    and 1 if it's invisible and without an ellipsis.  */
 29074 
 29075 int
 29076 invisible_prop (Lisp_Object propval, Lisp_Object list)
 29077 {
 29078   Lisp_Object tail, proptail;
 29079 
 29080   for (tail = list; CONSP (tail); tail = XCDR (tail))
 29081     {
 29082       register Lisp_Object tem;
 29083       tem = XCAR (tail);
 29084       if (EQ (propval, tem))
 29085         return 1;
 29086       if (CONSP (tem) && EQ (propval, XCAR (tem)))
 29087         return NILP (XCDR (tem)) ? 1 : 2;
 29088     }
 29089 
 29090   if (CONSP (propval))
 29091     {
 29092       for (proptail = propval; CONSP (proptail); proptail = XCDR (proptail))
 29093         {
 29094           Lisp_Object propelt;
 29095           propelt = XCAR (proptail);
 29096           for (tail = list; CONSP (tail); tail = XCDR (tail))
 29097             {
 29098               register Lisp_Object tem;
 29099               tem = XCAR (tail);
 29100               if (EQ (propelt, tem))
 29101                 return 1;
 29102               if (CONSP (tem) && EQ (propelt, XCAR (tem)))
 29103                 return NILP (XCDR (tem)) ? 1 : 2;
 29104             }
 29105         }
 29106     }
 29107 
 29108   return 0;
 29109 }
 29110 
 29111 DEFUN ("invisible-p", Finvisible_p, Sinvisible_p, 1, 1, 0,
 29112        doc: /* Non-nil if text properties at POS cause text there to be currently invisible.
 29113 POS should be a marker or a buffer position; the value of the `invisible'
 29114 property at that position in the current buffer is examined.
 29115 POS can also be the actual value of the `invisible' text or overlay
 29116 property of the text of interest, in which case the value itself is
 29117 examined.
 29118 
 29119 The non-nil value returned can be t for currently invisible text that is
 29120 entirely hidden on display, or some other non-nil, non-t value if the
 29121 text is replaced by an ellipsis.
 29122 
 29123 Note that whether text with `invisible' property is actually hidden on
 29124 display may depend on `buffer-invisibility-spec', which see.  */)
 29125   (Lisp_Object pos)
 29126 {
 29127   Lisp_Object prop
 29128     = (FIXNATP (pos) || MARKERP (pos)
 29129        ? Fget_char_property (pos, Qinvisible, Qnil)
 29130        : pos);
 29131   int invis = TEXT_PROP_MEANS_INVISIBLE (prop);
 29132   return (invis == 0 ? Qnil
 29133           : invis == 1 ? Qt
 29134           : make_fixnum (invis));
 29135 }
 29136 
 29137 /* Calculate a width or height in pixels from a specification using
 29138    the following elements:
 29139 
 29140    SPEC ::=
 29141      NUM      - a (fractional) multiple of the default font width/height
 29142      (NUM)    - specifies exactly NUM pixels
 29143      UNIT     - a fixed number of pixels, see below.
 29144      ELEMENT  - size of a display element in pixels, see below.
 29145      (NUM . SPEC) - equals NUM * SPEC
 29146      (+ SPEC SPEC ...)  - add pixel values
 29147      (- SPEC SPEC ...)  - subtract pixel values
 29148      (- SPEC)           - negate pixel value
 29149 
 29150    NUM ::=
 29151      INT or FLOAT   - a number constant
 29152      SYMBOL         - use symbol's (buffer local) variable binding.
 29153 
 29154    UNIT ::=
 29155      in       - pixels per inch  *)
 29156      mm       - pixels per 1/1000 meter  *)
 29157      cm       - pixels per 1/100 meter   *)
 29158      width    - width of current font in pixels.
 29159      height   - height of current font in pixels.
 29160 
 29161      *) using the ratio(s) defined in display-pixels-per-inch.
 29162 
 29163    ELEMENT ::=
 29164 
 29165      left-fringe          - left fringe width in pixels
 29166      right-fringe         - right fringe width in pixels
 29167 
 29168      left-margin          - left margin width in pixels
 29169      right-margin         - right margin width in pixels
 29170 
 29171      scroll-bar           - scroll-bar area width in pixels
 29172 
 29173    Examples:
 29174 
 29175    Pixels corresponding to 5 inches:
 29176      (5 . in)
 29177 
 29178    Total width of non-text areas on left side of window (if scroll-bar is on left):
 29179      '(space :width (+ left-fringe left-margin scroll-bar))
 29180 
 29181    Align to first text column (in header line):
 29182      '(space :align-to 0)
 29183 
 29184    Align to middle of text area minus half the width of variable `my-image'
 29185    containing a loaded image:
 29186      '(space :align-to (0.5 . (- text my-image)))
 29187 
 29188    Width of left margin minus width of 1 character in the default font:
 29189      '(space :width (- left-margin 1))
 29190 
 29191    Width of left margin minus width of 2 characters in the current font:
 29192      '(space :width (- left-margin (2 . width)))
 29193 
 29194    Center 1 character over left-margin (in header line):
 29195      '(space :align-to (+ left-margin (0.5 . left-margin) -0.5))
 29196 
 29197    Different ways to express width of left fringe plus left margin minus one pixel:
 29198      '(space :width (- (+ left-fringe left-margin) (1)))
 29199      '(space :width (+ left-fringe left-margin (- (1))))
 29200      '(space :width (+ left-fringe left-margin (-1)))
 29201 
 29202    If ALIGN_TO is NULL, returns the result in *RES.  If ALIGN_TO is
 29203    non-NULL, the value of *ALIGN_TO is a window-relative pixel
 29204    coordinate, and *RES is the additional pixel width from that point
 29205    till the end of the stretch glyph.
 29206 
 29207    WIDTH_P non-zero means take the width dimension or X coordinate of
 29208    the object specified by PROP, WIDTH_P zero means take the height
 29209    dimension or the Y coordinate.  (Therefore, if ALIGN_TO is
 29210    non-NULL, WIDTH_P should be non-zero.)
 29211 
 29212    FONT is the font of the face of the surrounding text.
 29213 
 29214    The return value is non-zero if width or height were successfully
 29215    calculated, i.e. if PROP is a valid spec.  */
 29216 
 29217 static bool
 29218 calc_pixel_width_or_height (double *res, struct it *it, Lisp_Object prop,
 29219                             struct font *font, bool width_p, int *align_to)
 29220 {
 29221   /* Don't adjust for line number if we didn't yet produce it for this
 29222      screen line.  This is for when this function is called from
 29223      move_it_in_display_line_to that was called by display_line to get
 29224      past the glyphs hscrolled off the left side of the window.  */
 29225   int lnum_pixel_width = it->line_number_produced_p ? it->lnum_pixel_width : 0;
 29226   double pixels;
 29227 
 29228 # define OK_PIXELS(val) (*res = (val), true)
 29229 # define OK_ALIGN_TO(val) (*align_to = (val), true)
 29230 
 29231   if (NILP (prop))
 29232     return OK_PIXELS (0);
 29233 
 29234   eassert (FRAME_LIVE_P (it->f));
 29235 
 29236   if (SYMBOLP (prop))
 29237     {
 29238       if (SCHARS (SYMBOL_NAME (prop)) == 2)
 29239         {
 29240           char *unit = SSDATA (SYMBOL_NAME (prop));
 29241 
 29242           /* The UNIT expression, e.g. as part of (NUM . UNIT).  */
 29243           if (unit[0] == 'i' && unit[1] == 'n')
 29244             pixels = 1.0;
 29245           else if (unit[0] == 'm' && unit[1] == 'm')
 29246             pixels = 25.4;
 29247           else if (unit[0] == 'c' && unit[1] == 'm')
 29248             pixels = 2.54;
 29249           else
 29250             pixels = 0;
 29251           if (pixels > 0)
 29252             {
 29253               double ppi = (width_p ? FRAME_RES_X (it->f)
 29254                             : FRAME_RES_Y (it->f));
 29255 
 29256               if (ppi > 0)
 29257                 return OK_PIXELS (ppi / pixels);
 29258               return false;
 29259             }
 29260         }
 29261 
 29262 #ifdef HAVE_WINDOW_SYSTEM
 29263       /* 'height': the height of FONT.  */
 29264       if (EQ (prop, Qheight))
 29265         return OK_PIXELS (font
 29266                           ? normal_char_height (font, -1)
 29267                           : FRAME_LINE_HEIGHT (it->f));
 29268       /* 'width': the width of FONT.  */
 29269       if (EQ (prop, Qwidth))
 29270         return OK_PIXELS (font
 29271                           ? FONT_WIDTH (font)
 29272                           : FRAME_COLUMN_WIDTH (it->f));
 29273 #else
 29274       if (EQ (prop, Qheight) || EQ (prop, Qwidth))
 29275         return OK_PIXELS (1);
 29276 #endif
 29277 
 29278       /* 'text': the width or height of the text area.  */
 29279       if (EQ (prop, Qtext))
 29280           return OK_PIXELS (width_p
 29281                             ? (window_box_width (it->w, TEXT_AREA)
 29282                                - lnum_pixel_width)
 29283                             : WINDOW_BOX_HEIGHT_NO_MODE_LINE (it->w));
 29284 
 29285       /* ':align_to'.  First time we compute the value, window
 29286          elements are interpreted as the position of the element's
 29287          left edge.  */
 29288       if (align_to && *align_to < 0)
 29289         {
 29290           *res = 0;
 29291           /* 'left': left edge of the text area.  */
 29292           if (EQ (prop, Qleft))
 29293             return OK_ALIGN_TO (window_box_left_offset (it->w, TEXT_AREA)
 29294                                 + lnum_pixel_width);
 29295           /* 'right': right edge of the text area.  */
 29296           if (EQ (prop, Qright))
 29297             return OK_ALIGN_TO (window_box_right_offset (it->w, TEXT_AREA));
 29298           /* 'center': the center of the text area.  */
 29299           if (EQ (prop, Qcenter))
 29300             return OK_ALIGN_TO (window_box_left_offset (it->w, TEXT_AREA)
 29301                                 + lnum_pixel_width
 29302                                 + window_box_width (it->w, TEXT_AREA) / 2);
 29303           /* 'left-fringe': left edge of the left fringe.  */
 29304           if (EQ (prop, Qleft_fringe))
 29305             return OK_ALIGN_TO (WINDOW_HAS_FRINGES_OUTSIDE_MARGINS (it->w)
 29306                                 ? WINDOW_LEFT_SCROLL_BAR_AREA_WIDTH (it->w)
 29307                                 : window_box_right_offset (it->w, LEFT_MARGIN_AREA));
 29308           /* 'right-fringe': left edge of the right fringe.  */
 29309           if (EQ (prop, Qright_fringe))
 29310             return OK_ALIGN_TO (WINDOW_HAS_FRINGES_OUTSIDE_MARGINS (it->w)
 29311                                 ? window_box_right_offset (it->w, RIGHT_MARGIN_AREA)
 29312                                 : window_box_right_offset (it->w, TEXT_AREA));
 29313           /* 'left-margin': left edge of the left display margin.  */
 29314           if (EQ (prop, Qleft_margin))
 29315             return OK_ALIGN_TO (window_box_left_offset (it->w, LEFT_MARGIN_AREA));
 29316           /* 'right-margin': left edge of the right display margin.  */
 29317           if (EQ (prop, Qright_margin))
 29318             return OK_ALIGN_TO (window_box_left_offset (it->w, RIGHT_MARGIN_AREA));
 29319           /* 'scroll-bar': left edge of the vertical scroll bar.  */
 29320           if (EQ (prop, Qscroll_bar))
 29321             return OK_ALIGN_TO (WINDOW_HAS_VERTICAL_SCROLL_BAR_ON_LEFT (it->w)
 29322                                 ? 0
 29323                                 : (window_box_right_offset (it->w, RIGHT_MARGIN_AREA)
 29324                                    + (WINDOW_HAS_FRINGES_OUTSIDE_MARGINS (it->w)
 29325                                       ? WINDOW_RIGHT_FRINGE_WIDTH (it->w)
 29326                                       : 0)));
 29327         }
 29328       else
 29329         {
 29330           /* Otherwise, the elements stand for their width.  */
 29331           if (EQ (prop, Qleft_fringe))
 29332             return OK_PIXELS (WINDOW_LEFT_FRINGE_WIDTH (it->w));
 29333           if (EQ (prop, Qright_fringe))
 29334             return OK_PIXELS (WINDOW_RIGHT_FRINGE_WIDTH (it->w));
 29335           if (EQ (prop, Qleft_margin))
 29336             return OK_PIXELS (WINDOW_LEFT_MARGIN_WIDTH (it->w));
 29337           if (EQ (prop, Qright_margin))
 29338             return OK_PIXELS (WINDOW_RIGHT_MARGIN_WIDTH (it->w));
 29339           if (EQ (prop, Qscroll_bar))
 29340             return OK_PIXELS (WINDOW_SCROLL_BAR_AREA_WIDTH (it->w));
 29341         }
 29342 
 29343       prop = buffer_local_value (prop, it->w->contents);
 29344       if (BASE_EQ (prop, Qunbound))
 29345         prop = Qnil;
 29346     }
 29347 
 29348   if (NUMBERP (prop))
 29349     {
 29350       int base_unit = (width_p
 29351                        ? FRAME_COLUMN_WIDTH (it->f)
 29352                        : FRAME_LINE_HEIGHT (it->f));
 29353       if (width_p && align_to && *align_to < 0)
 29354         return OK_PIXELS (XFLOATINT (prop) * base_unit + lnum_pixel_width);
 29355       return OK_PIXELS (XFLOATINT (prop) * base_unit);
 29356     }
 29357 
 29358   if (CONSP (prop))
 29359     {
 29360       Lisp_Object car = XCAR (prop);
 29361       Lisp_Object cdr = XCDR (prop);
 29362 
 29363       if (SYMBOLP (car))
 29364         {
 29365 #ifdef HAVE_WINDOW_SYSTEM
 29366           /* '(image PROPS...)': width or height of the specified image.  */
 29367           if (FRAME_WINDOW_P (it->f)
 29368               && valid_image_p (prop))
 29369             {
 29370               ptrdiff_t id = lookup_image (it->f, prop, it->face_id);
 29371               struct image *img = IMAGE_FROM_ID (it->f, id);
 29372 
 29373               return OK_PIXELS (width_p ? img->width : img->height);
 29374             }
 29375           /* '(xwidget PROPS...)': dimensions of the specified xwidget.  */
 29376           if (FRAME_WINDOW_P (it->f) && valid_xwidget_spec_p (prop))
 29377             {
 29378               /* TODO: Don't return dummy size.  */
 29379               return OK_PIXELS (100);
 29380             }
 29381 #endif
 29382           /* '(+ EXPR...)' or '(- EXPR...)' add or subtract
 29383              recursively calculated values.  */
 29384           if (EQ (car, Qplus) || EQ (car, Qminus))
 29385             {
 29386               bool first = true;
 29387               double px;
 29388 
 29389               pixels = 0;
 29390               while (CONSP (cdr))
 29391                 {
 29392                   if (!calc_pixel_width_or_height (&px, it, XCAR (cdr),
 29393                                                    font, width_p, align_to))
 29394                     return false;
 29395                   if (first)
 29396                     pixels = (EQ (car, Qplus) ? px : -px), first = false;
 29397                   else
 29398                     pixels += px;
 29399                   cdr = XCDR (cdr);
 29400                 }
 29401               if (EQ (car, Qminus))
 29402                 pixels = -pixels;
 29403               return OK_PIXELS (pixels);
 29404             }
 29405 
 29406           car = buffer_local_value (car, it->w->contents);
 29407           if (BASE_EQ (car, Qunbound))
 29408             car = Qnil;
 29409         }
 29410 
 29411       /* '(NUM)': absolute number of pixels.  */
 29412       if (NUMBERP (car))
 29413         {
 29414           double fact;
 29415           int offset =
 29416             width_p && align_to && *align_to < 0 ? lnum_pixel_width : 0;
 29417           pixels = XFLOATINT (car);
 29418           if (NILP (cdr))
 29419             return OK_PIXELS (pixels + offset);
 29420           if (calc_pixel_width_or_height (&fact, it, cdr,
 29421                                           font, width_p, align_to))
 29422             return OK_PIXELS (pixels * fact + offset);
 29423           return false;
 29424         }
 29425 
 29426       return false;
 29427     }
 29428 
 29429   return false;
 29430 }
 29431 
 29432 void
 29433 get_font_ascent_descent (struct font *font, int *ascent, int *descent)
 29434 {
 29435 #ifdef HAVE_WINDOW_SYSTEM
 29436   normal_char_ascent_descent (font, -1, ascent, descent);
 29437 #else
 29438   *ascent = 1;
 29439   *descent = 0;
 29440 #endif
 29441 }
 29442 
 29443 
 29444 /***********************************************************************
 29445                              Glyph Display
 29446  ***********************************************************************/
 29447 
 29448 #ifdef HAVE_WINDOW_SYSTEM
 29449 
 29450 #ifdef GLYPH_DEBUG
 29451 
 29452 extern void dump_glyph_string (struct glyph_string *) EXTERNALLY_VISIBLE;
 29453 void
 29454 dump_glyph_string (struct glyph_string *s)
 29455 {
 29456   fputs ("glyph string\n", stderr);
 29457   fprintf (stderr, "  x, y, w, h = %d, %d, %d, %d\n",
 29458            s->x, s->y, s->width, s->height);
 29459   fprintf (stderr, "  ybase = %d\n", s->ybase);
 29460   fprintf (stderr, "  hl = %u\n", s->hl);
 29461   fprintf (stderr, "  left overhang = %d, right = %d\n",
 29462            s->left_overhang, s->right_overhang);
 29463   fprintf (stderr, "  nchars = %d\n", s->nchars);
 29464   fprintf (stderr, "  extends to end of line = %d\n",
 29465            s->extends_to_end_of_line_p);
 29466   fprintf (stderr, "  font height = %d\n", FONT_HEIGHT (s->font));
 29467   fprintf (stderr, "  bg width = %d\n", s->background_width);
 29468 }
 29469 
 29470 #endif /* GLYPH_DEBUG */
 29471 
 29472 /* Initialize glyph string S.  CHAR2B is a suitably allocated vector
 29473    of 2-byte unsigned integers for S; it can't be allocated in
 29474    init_glyph_string because it must be allocated via `alloca'.  W
 29475    is the window on which S is drawn.  ROW and AREA are the glyph row
 29476    and area within the row from which S is constructed.  START is the
 29477    index of the first glyph structure covered by S.  HL is a
 29478    face-override for drawing S.  */
 29479 
 29480 #ifdef HAVE_NTGUI
 29481 /* We set inhibit-quit here due to paranoia: get_frame_dc acquires the
 29482    critical section, and we cannot QUIT while we hold the critical
 29483    section.  If any of the code run by callers of ALLOCATE_HDC happens
 29484    to call Lisp (might be possible due to all the hooks lying around),
 29485    we must prevent it from quitting.  */
 29486 # define ALLOCATE_HDC(hdc, f)                   \
 29487   Lisp_Object prev_quit = Vinhibit_quit;        \
 29488   Vinhibit_quit = Qt;                           \
 29489   HDC hdc = get_frame_dc ((f))
 29490 # define RELEASE_HDC(hdc, f)                    \
 29491   release_frame_dc ((f), (hdc));                \
 29492   Vinhibit_quit = prev_quit
 29493 #else
 29494 # define ALLOCATE_HDC(hdc, f)
 29495 # define RELEASE_HDC(hdc, f)
 29496 #endif
 29497 
 29498 static void
 29499 init_glyph_string (struct glyph_string *s,
 29500 #ifdef HAVE_NTGUI
 29501                    HDC hdc,
 29502 #endif
 29503                    unsigned *char2b, struct window *w, struct glyph_row *row,
 29504                    enum glyph_row_area area, int start, enum draw_glyphs_face hl)
 29505 {
 29506   memset (s, 0, sizeof *s);
 29507   s->w = w;
 29508   s->f = XFRAME (w->frame);
 29509 #ifdef HAVE_NTGUI
 29510   s->hdc = hdc;
 29511 #endif
 29512   s->char2b = char2b;
 29513   s->hl = hl;
 29514   s->row = row;
 29515   s->area = area;
 29516   s->first_glyph = row->glyphs[area] + start;
 29517   s->height = row->height;
 29518   s->y = WINDOW_TO_FRAME_PIXEL_Y (w, row->y);
 29519   s->ybase = s->y + row->ascent;
 29520 }
 29521 
 29522 
 29523 /* Append the list of glyph strings with head H and tail T to the list
 29524    with head *HEAD and tail *TAIL.  Set *HEAD and *TAIL to the result.  */
 29525 
 29526 static void
 29527 append_glyph_string_lists (struct glyph_string **head, struct glyph_string **tail,
 29528                            struct glyph_string *h, struct glyph_string *t)
 29529 {
 29530   if (h)
 29531     {
 29532       if (*head)
 29533         (*tail)->next = h;
 29534       else
 29535         *head = h;
 29536       h->prev = *tail;
 29537       *tail = t;
 29538     }
 29539 }
 29540 
 29541 
 29542 /* Prepend the list of glyph strings with head H and tail T to the
 29543    list with head *HEAD and tail *TAIL.  Set *HEAD and *TAIL to the
 29544    result.  */
 29545 
 29546 static void
 29547 prepend_glyph_string_lists (struct glyph_string **head, struct glyph_string **tail,
 29548                             struct glyph_string *h, struct glyph_string *t)
 29549 {
 29550   if (h)
 29551     {
 29552       if (*head)
 29553         (*head)->prev = t;
 29554       else
 29555         *tail = t;
 29556       t->next = *head;
 29557       *head = h;
 29558     }
 29559 }
 29560 
 29561 
 29562 /* Append glyph string S to the list with head *HEAD and tail *TAIL.
 29563    Set *HEAD and *TAIL to the resulting list.  */
 29564 
 29565 static void
 29566 append_glyph_string (struct glyph_string **head, struct glyph_string **tail,
 29567                      struct glyph_string *s)
 29568 {
 29569   s->next = s->prev = NULL;
 29570   append_glyph_string_lists (head, tail, s, s);
 29571 }
 29572 
 29573 
 29574 /* Get face and two-byte form of character C in face FACE_ID on frame F.
 29575    The encoding of C is returned in *CHAR2B.  DISPLAY_P means
 29576    make sure that X resources for the face returned are allocated.
 29577    Value is a pointer to a realized face that is ready for display if
 29578    DISPLAY_P.  */
 29579 
 29580 static struct face *
 29581 get_char_face_and_encoding (struct frame *f, int c, int face_id,
 29582                             unsigned *char2b, bool display_p)
 29583 {
 29584   struct face *face = FACE_FROM_ID (f, face_id);
 29585   unsigned code = 0;
 29586 
 29587   if (face->font)
 29588     {
 29589       code = face->font->driver->encode_char (face->font, c);
 29590 
 29591       if (code == FONT_INVALID_CODE)
 29592         code = 0;
 29593     }
 29594   /* Ensure that the code is only 2 bytes wide.  */
 29595   *char2b = code & 0xFFFF;
 29596 
 29597   /* Make sure X resources of the face are allocated.  */
 29598 #ifdef HAVE_X_WINDOWS
 29599   if (display_p)
 29600 #endif
 29601     {
 29602       eassert (face != NULL);
 29603       prepare_face_for_display (f, face);
 29604     }
 29605 
 29606   return face;
 29607 }
 29608 
 29609 
 29610 /* Get face and two-byte form of character glyph GLYPH on frame F.
 29611    The encoding of GLYPH->u.ch is returned in *CHAR2B.  Value is
 29612    a pointer to a realized face that is ready for display.  */
 29613 
 29614 static struct face *
 29615 get_glyph_face_and_encoding (struct frame *f, struct glyph *glyph,
 29616                              unsigned *char2b)
 29617 {
 29618   struct face *face;
 29619   unsigned code = 0;
 29620 
 29621   eassert (glyph->type == CHAR_GLYPH);
 29622   face = FACE_FROM_ID (f, glyph->face_id);
 29623 
 29624   /* Make sure X resources of the face are allocated.  */
 29625   prepare_face_for_display (f, face);
 29626 
 29627   if (face->font)
 29628     {
 29629       if (CHAR_BYTE8_P (glyph->u.ch))
 29630         code = CHAR_TO_BYTE8 (glyph->u.ch);
 29631       else
 29632         code = face->font->driver->encode_char (face->font, glyph->u.ch);
 29633 
 29634       if (code == FONT_INVALID_CODE)
 29635         code = 0;
 29636     }
 29637 
 29638   /* Ensure that the code is only 2 bytes wide.  */
 29639   *char2b = code & 0xFFFF;
 29640   return face;
 29641 }
 29642 
 29643 
 29644 /* Get glyph code of character C in FONT in the two-byte form CHAR2B.
 29645    Return true iff FONT has a glyph for C.  */
 29646 
 29647 static bool
 29648 get_char_glyph_code (int c, struct font *font, unsigned *char2b)
 29649 {
 29650   unsigned code;
 29651 
 29652   if (CHAR_BYTE8_P (c))
 29653     code = CHAR_TO_BYTE8 (c);
 29654   else
 29655     code = font->driver->encode_char (font, c);
 29656 
 29657   if (code == FONT_INVALID_CODE)
 29658     return false;
 29659 
 29660   /* Ensure that the code is only 2 bytes wide.  */
 29661   *char2b = code & 0xFFFF;
 29662   return true;
 29663 }
 29664 
 29665 
 29666 /* Fill glyph string S with composition components specified by S->cmp.
 29667 
 29668    BASE_FACE is the base face of the composition.
 29669    S->cmp_from is the index of the first component for S.
 29670 
 29671    OVERLAPS non-zero means S should draw the foreground only, and use
 29672    its physical height for clipping.  See also draw_glyphs.
 29673 
 29674    Value is the index of a component not in S.  */
 29675 
 29676 static int
 29677 fill_composite_glyph_string (struct glyph_string *s, struct face *base_face,
 29678                              int overlaps)
 29679 {
 29680   int i;
 29681   /* For all glyphs of this composition, starting at the offset
 29682      S->cmp_from, until we reach the end of the definition or encounter a
 29683      glyph that requires the different face, add it to S.  */
 29684   struct face *face;
 29685 
 29686   eassert (s);
 29687 
 29688   s->for_overlaps = overlaps;
 29689   s->face = NULL;
 29690   s->font = NULL;
 29691   for (i = s->cmp_from; i < s->cmp->glyph_len; i++)
 29692     {
 29693       int c = COMPOSITION_GLYPH (s->cmp, i);
 29694 
 29695       /* TAB in a composition means display glyphs with padding space
 29696          on the left or right.  */
 29697       if (c != '\t')
 29698         {
 29699           int face_id = FACE_FOR_CHAR (s->f, base_face->ascii_face, c,
 29700                                        -1, Qnil);
 29701 
 29702           face = get_char_face_and_encoding (s->f, c, face_id,
 29703                                              s->char2b + i, true);
 29704           if (face)
 29705             {
 29706               if (! s->face)
 29707                 {
 29708                   s->face = face;
 29709                   s->font = s->face->font;
 29710                 }
 29711               else if (s->face != face)
 29712                 break;
 29713             }
 29714         }
 29715       ++s->nchars;
 29716     }
 29717   s->cmp_to = i;
 29718 
 29719   if (s->face == NULL)
 29720     {
 29721       s->face = base_face->ascii_face;
 29722       s->font = s->face->font;
 29723     }
 29724 
 29725   if (s->hl == DRAW_MOUSE_FACE
 29726       || (s->hl == DRAW_CURSOR
 29727           && MATRIX_ROW (s->w->current_matrix,
 29728                          s->w->phys_cursor.vpos)->mouse_face_p
 29729           && cursor_in_mouse_face_p (s->w)))
 29730     {
 29731       int c = COMPOSITION_GLYPH (s->cmp, 0);
 29732       Mouse_HLInfo *hlinfo = MOUSE_HL_INFO (s->f);
 29733       s->face = FACE_FROM_ID_OR_NULL (s->f, hlinfo->mouse_face_face_id);
 29734       if (!s->face)
 29735         s->face = FACE_FROM_ID (s->f, MOUSE_FACE_ID);
 29736 
 29737       s->face = FACE_FROM_ID (s->f, FACE_FOR_CHAR (s->f, s->face, c, -1, Qnil));
 29738       prepare_face_for_display (s->f, s->face);
 29739     }
 29740 
 29741   /* All glyph strings for the same composition has the same width,
 29742      i.e. the width set for the first component of the composition.  */
 29743   s->width = s->first_glyph->pixel_width;
 29744 
 29745   /* If the specified font could not be loaded, use the frame's
 29746      default font, but record the fact that we couldn't load it in
 29747      the glyph string so that we can draw rectangles for the
 29748      characters of the glyph string.  */
 29749   if (s->font == NULL)
 29750     {
 29751       s->font_not_found_p = true;
 29752       s->font = FRAME_FONT (s->f);
 29753     }
 29754 
 29755   /* Adjust base line for subscript/superscript text.  */
 29756   s->ybase += s->first_glyph->voffset;
 29757 
 29758   return s->cmp_to;
 29759 }
 29760 
 29761 static int
 29762 fill_gstring_glyph_string (struct glyph_string *s, int face_id,
 29763                            int start, int end, int overlaps)
 29764 {
 29765   struct glyph *glyph, *last;
 29766   int voffset;
 29767   Lisp_Object lgstring;
 29768   int i;
 29769   bool glyph_not_available_p;
 29770 
 29771   s->for_overlaps = overlaps;
 29772   glyph = s->row->glyphs[s->area] + start;
 29773   last = s->row->glyphs[s->area] + end;
 29774   voffset = glyph->voffset;
 29775   glyph_not_available_p = glyph->glyph_not_available_p;
 29776   s->cmp_id = glyph->u.cmp.id;
 29777   s->cmp_from = glyph->slice.cmp.from;
 29778   s->cmp_to = glyph->slice.cmp.to + 1;
 29779   if (s->hl == DRAW_MOUSE_FACE
 29780       || (s->hl == DRAW_CURSOR
 29781           && MATRIX_ROW (s->w->current_matrix,
 29782                          s->w->phys_cursor.vpos)->mouse_face_p
 29783           && cursor_in_mouse_face_p (s->w)))
 29784     {
 29785       Mouse_HLInfo *hlinfo = MOUSE_HL_INFO (s->f);
 29786       s->face = FACE_FROM_ID_OR_NULL (s->f, hlinfo->mouse_face_face_id);
 29787       if (!s->face)
 29788         s->face = FACE_FROM_ID (s->f, MOUSE_FACE_ID);
 29789       prepare_face_for_display (s->f, s->face);
 29790     }
 29791   else
 29792     s->face = FACE_FROM_ID (s->f, face_id);
 29793   lgstring = composition_gstring_from_id (s->cmp_id);
 29794   s->font = XFONT_OBJECT (LGSTRING_FONT (lgstring));
 29795   /* The width of a composition glyph string is the sum of the
 29796      composition's glyph widths.  */
 29797   s->width = s->first_glyph->pixel_width;
 29798   glyph++;
 29799   while (glyph < last
 29800          && glyph->u.cmp.automatic
 29801          && glyph->u.cmp.id == s->cmp_id
 29802          && glyph->face_id == face_id
 29803          && s->cmp_to == glyph->slice.cmp.from
 29804          && glyph->glyph_not_available_p == glyph_not_available_p)
 29805     {
 29806       s->width += glyph->pixel_width;
 29807       s->cmp_to = (glyph++)->slice.cmp.to + 1;
 29808     }
 29809 
 29810   for (i = s->cmp_from; i < s->cmp_to; i++)
 29811     {
 29812       Lisp_Object lglyph = LGSTRING_GLYPH (lgstring, i);
 29813       unsigned code = LGLYPH_CODE (lglyph);
 29814 
 29815       /* Ensure that the code is only 2 bytes wide.  */
 29816       s->char2b[i] = code & 0xFFFF;
 29817     }
 29818 
 29819   /* If the specified font could not be loaded, record that fact in
 29820      S->font_not_found_p so that we can draw rectangles for the
 29821      characters of the glyph string.  */
 29822   if (glyph_not_available_p)
 29823     s->font_not_found_p = true;
 29824 
 29825   /* Adjust base line for subscript/superscript text.  */
 29826   s->ybase += voffset;
 29827 
 29828   return glyph - s->row->glyphs[s->area];
 29829 }
 29830 
 29831 
 29832 /* Fill glyph string S from a sequence glyphs for glyphless characters.
 29833    See the comment of fill_glyph_string for arguments.
 29834    Value is the index of the first glyph not in S.  */
 29835 
 29836 
 29837 static int
 29838 fill_glyphless_glyph_string (struct glyph_string *s, int face_id,
 29839                              int start, int end, int overlaps)
 29840 {
 29841   struct glyph *glyph, *last;
 29842   int voffset;
 29843 
 29844   eassert (s->first_glyph->type == GLYPHLESS_GLYPH);
 29845   s->for_overlaps = overlaps;
 29846   glyph = s->row->glyphs[s->area] + start;
 29847   last = s->row->glyphs[s->area] + end;
 29848   voffset = glyph->voffset;
 29849   s->face = FACE_FROM_ID (s->f, face_id);
 29850   s->font = s->face->font ? s->face->font : FRAME_FONT (s->f);
 29851   if (s->hl == DRAW_MOUSE_FACE
 29852       || (s->hl == DRAW_CURSOR
 29853           && MATRIX_ROW (s->w->current_matrix,
 29854                          s->w->phys_cursor.vpos)->mouse_face_p
 29855           && cursor_in_mouse_face_p (s->w)))
 29856     {
 29857       Mouse_HLInfo *hlinfo = MOUSE_HL_INFO (s->f);
 29858       s->face = FACE_FROM_ID_OR_NULL (s->f, hlinfo->mouse_face_face_id);
 29859       if (!s->face)
 29860         s->face = FACE_FROM_ID (s->f, MOUSE_FACE_ID);
 29861       prepare_face_for_display (s->f, s->face);
 29862     }
 29863   s->nchars = 1;
 29864   s->width = glyph->pixel_width;
 29865   glyph++;
 29866   while (glyph < last
 29867          && glyph->type == GLYPHLESS_GLYPH
 29868          && glyph->voffset == voffset
 29869          && glyph->face_id == face_id)
 29870     {
 29871       s->nchars++;
 29872       s->width += glyph->pixel_width;
 29873       glyph++;
 29874     }
 29875   s->ybase += voffset;
 29876   return glyph - s->row->glyphs[s->area];
 29877 }
 29878 
 29879 
 29880 /* Fill glyph string S from a sequence of character glyphs.
 29881 
 29882    FACE_ID is the face id of the string.  START is the index of the
 29883    first glyph to consider, END is the index of the last + 1.
 29884    OVERLAPS non-zero means S should draw the foreground only, and use
 29885    its physical height for clipping.  See also draw_glyphs.
 29886 
 29887    Value is the index of the first glyph not in S.  */
 29888 
 29889 static int
 29890 fill_glyph_string (struct glyph_string *s, int face_id,
 29891                    int start, int end, int overlaps)
 29892 {
 29893   struct glyph *glyph, *last;
 29894   int voffset;
 29895   bool glyph_not_available_p;
 29896 
 29897   eassert (s->f == XFRAME (s->w->frame));
 29898   eassert (s->nchars == 0);
 29899   eassert (start >= 0 && end > start);
 29900 
 29901   s->for_overlaps = overlaps;
 29902   glyph = s->row->glyphs[s->area] + start;
 29903   last = s->row->glyphs[s->area] + end;
 29904   voffset = glyph->voffset;
 29905   s->padding_p = glyph->padding_p;
 29906   glyph_not_available_p = glyph->glyph_not_available_p;
 29907 
 29908   while (glyph < last
 29909          && glyph->type == CHAR_GLYPH
 29910          && glyph->voffset == voffset
 29911          /* Same face id implies same font, nowadays.  */
 29912          && glyph->face_id == face_id
 29913          && glyph->glyph_not_available_p == glyph_not_available_p)
 29914     {
 29915       s->face = get_glyph_face_and_encoding (s->f, glyph,
 29916                                              s->char2b + s->nchars);
 29917       ++s->nchars;
 29918       eassert (s->nchars <= end - start);
 29919       s->width += glyph->pixel_width;
 29920       if (glyph++->padding_p != s->padding_p)
 29921         break;
 29922     }
 29923 
 29924   s->font = s->face->font;
 29925 
 29926   if (s->hl == DRAW_MOUSE_FACE
 29927       || (s->hl == DRAW_CURSOR
 29928           && MATRIX_ROW (s->w->current_matrix,
 29929                          s->w->phys_cursor.vpos)->mouse_face_p
 29930           && cursor_in_mouse_face_p (s->w)))
 29931     {
 29932       Mouse_HLInfo *hlinfo = MOUSE_HL_INFO (s->f);
 29933       s->face = FACE_FROM_ID_OR_NULL (s->f, hlinfo->mouse_face_face_id);
 29934       if (!s->face)
 29935         s->face = FACE_FROM_ID (s->f, MOUSE_FACE_ID);
 29936       s->face
 29937         = FACE_FROM_ID (s->f, FACE_FOR_CHAR (s->f, s->face,
 29938                                              s->first_glyph->u.ch, -1, Qnil));
 29939       prepare_face_for_display (s->f, s->face);
 29940     }
 29941 
 29942   /* If the specified font could not be loaded, use the frame's font,
 29943      but record the fact that we couldn't load it in
 29944      S->font_not_found_p so that we can draw rectangles for the
 29945      characters of the glyph string.  */
 29946   if (s->font == NULL || glyph_not_available_p)
 29947     {
 29948       s->font_not_found_p = true;
 29949       s->font = FRAME_FONT (s->f);
 29950     }
 29951 
 29952   /* Adjust base line for subscript/superscript text.  */
 29953   s->ybase += voffset;
 29954 
 29955   eassert (s->face && s->face->gc);
 29956   return glyph - s->row->glyphs[s->area];
 29957 }
 29958 
 29959 
 29960 /* Fill glyph string S from image glyph S->first_glyph.  */
 29961 
 29962 static void
 29963 fill_image_glyph_string (struct glyph_string *s)
 29964 {
 29965   eassert (s->first_glyph->type == IMAGE_GLYPH);
 29966   s->img = IMAGE_FROM_ID (s->f, s->first_glyph->u.img_id);
 29967   eassert (s->img);
 29968   s->slice = s->first_glyph->slice.img;
 29969   s->face = FACE_FROM_ID (s->f, s->first_glyph->face_id);
 29970   s->font = s->face->font;
 29971   if (s->hl == DRAW_MOUSE_FACE
 29972       || (s->hl == DRAW_CURSOR
 29973           && MATRIX_ROW (s->w->current_matrix,
 29974                          s->w->phys_cursor.vpos)->mouse_face_p
 29975           && cursor_in_mouse_face_p (s->w)))
 29976     {
 29977       Mouse_HLInfo *hlinfo = MOUSE_HL_INFO (s->f);
 29978       s->face = FACE_FROM_ID_OR_NULL (s->f, hlinfo->mouse_face_face_id);
 29979       if (!s->face)
 29980         s->face = FACE_FROM_ID (s->f, MOUSE_FACE_ID);
 29981       prepare_face_for_display (s->f, s->face);
 29982     }
 29983   s->width = s->first_glyph->pixel_width;
 29984 
 29985   /* Adjust base line for subscript/superscript text.  */
 29986   s->ybase += s->first_glyph->voffset;
 29987 }
 29988 
 29989 
 29990 #ifdef HAVE_XWIDGETS
 29991 static void
 29992 fill_xwidget_glyph_string (struct glyph_string *s)
 29993 {
 29994   eassert (s->first_glyph->type == XWIDGET_GLYPH);
 29995   s->face = FACE_FROM_ID (s->f, s->first_glyph->face_id);
 29996   s->font = s->face->font;
 29997   if (s->hl == DRAW_MOUSE_FACE
 29998       || (s->hl == DRAW_CURSOR
 29999           && MATRIX_ROW (s->w->current_matrix,
 30000                          s->w->phys_cursor.vpos)->mouse_face_p
 30001           && cursor_in_mouse_face_p (s->w)))
 30002     {
 30003       Mouse_HLInfo *hlinfo = MOUSE_HL_INFO (s->f);
 30004       s->face = FACE_FROM_ID_OR_NULL (s->f, hlinfo->mouse_face_face_id);
 30005       if (!s->face)
 30006         s->face = FACE_FROM_ID (s->f, MOUSE_FACE_ID);
 30007       prepare_face_for_display (s->f, s->face);
 30008     }
 30009   s->width = s->first_glyph->pixel_width;
 30010   s->ybase += s->first_glyph->voffset;
 30011   s->xwidget = xwidget_from_id (s->first_glyph->u.xwidget);
 30012 }
 30013 #endif
 30014 /* Fill glyph string S from a sequence of stretch glyphs.
 30015 
 30016    START is the index of the first glyph to consider,
 30017    END is the index of the last + 1.
 30018 
 30019    Value is the index of the first glyph not in S.  */
 30020 
 30021 static int
 30022 fill_stretch_glyph_string (struct glyph_string *s, int start, int end)
 30023 {
 30024   struct glyph *glyph, *last;
 30025   int voffset, face_id;
 30026 
 30027   eassert (s->first_glyph->type == STRETCH_GLYPH);
 30028 
 30029   glyph = s->row->glyphs[s->area] + start;
 30030   last = s->row->glyphs[s->area] + end;
 30031   face_id = glyph->face_id;
 30032   s->face = FACE_FROM_ID (s->f, face_id);
 30033   s->font = s->face->font;
 30034   if (s->hl == DRAW_MOUSE_FACE
 30035       || (s->hl == DRAW_CURSOR
 30036           && MATRIX_ROW (s->w->current_matrix,
 30037                          s->w->phys_cursor.vpos)->mouse_face_p
 30038           && cursor_in_mouse_face_p (s->w)))
 30039     {
 30040       Mouse_HLInfo *hlinfo = MOUSE_HL_INFO (s->f);
 30041       s->face = FACE_FROM_ID_OR_NULL (s->f, hlinfo->mouse_face_face_id);
 30042       if (!s->face)
 30043         s->face = FACE_FROM_ID (s->f, MOUSE_FACE_ID);
 30044       prepare_face_for_display (s->f, s->face);
 30045     }
 30046   s->width = glyph->pixel_width;
 30047   s->nchars = 1;
 30048   voffset = glyph->voffset;
 30049 
 30050   for (++glyph;
 30051        (glyph < last
 30052         && glyph->type == STRETCH_GLYPH
 30053         && glyph->voffset == voffset
 30054         && glyph->face_id == face_id);
 30055        ++glyph)
 30056     s->width += glyph->pixel_width;
 30057 
 30058   /* Adjust base line for subscript/superscript text.  */
 30059   s->ybase += voffset;
 30060 
 30061   /* The case that face->gc == 0 is handled when drawing the glyph
 30062      string by calling prepare_face_for_display.  */
 30063   eassert (s->face);
 30064   return glyph - s->row->glyphs[s->area];
 30065 }
 30066 
 30067 static struct font_metrics *
 30068 get_per_char_metric (struct font *font, const unsigned *char2b)
 30069 {
 30070   static struct font_metrics metrics;
 30071 
 30072   if (! font)
 30073     return NULL;
 30074   if (*char2b == FONT_INVALID_CODE)
 30075     return NULL;
 30076 
 30077   font->driver->text_extents (font, char2b, 1, &metrics);
 30078   return &metrics;
 30079 }
 30080 
 30081 /* A subroutine that computes "normal" values of ASCENT and DESCENT
 30082    for FONT.  Values are taken from font-global ones, except for fonts
 30083    that claim preposterously large values, but whose glyphs actually
 30084    have reasonable dimensions.  C is the character to use for metrics
 30085    if the font-global values are too large; if C is negative, the
 30086    function selects a default character.  */
 30087 static void
 30088 normal_char_ascent_descent (struct font *font, int c, int *ascent, int *descent)
 30089 {
 30090   *ascent = FONT_BASE (font);
 30091   *descent = FONT_DESCENT (font);
 30092 
 30093   if (FONT_TOO_HIGH (font))
 30094     {
 30095       unsigned char2b;
 30096 
 30097       /* Get metrics of C, defaulting to a reasonably sized ASCII
 30098          character.  */
 30099       if (get_char_glyph_code (c >= 0 ? c : '{', font, &char2b))
 30100         {
 30101           struct font_metrics *pcm = get_per_char_metric (font, &char2b);
 30102           eassume (pcm);
 30103 
 30104           if (!(pcm->width == 0 && pcm->rbearing == 0 && pcm->lbearing == 0))
 30105             {
 30106               /* We add 1 pixel to character dimensions as heuristics
 30107                  that produces nicer display, e.g. when the face has
 30108                  the box attribute.  */
 30109               *ascent = pcm->ascent + 1;
 30110               *descent = pcm->descent + 1;
 30111             }
 30112         }
 30113     }
 30114 }
 30115 
 30116 /* A subroutine that computes a reasonable "normal character height"
 30117    for fonts that claim preposterously large vertical dimensions, but
 30118    whose glyphs are actually reasonably sized.  C is the character
 30119    whose metrics to use for those fonts, or -1 for default
 30120    character.  */
 30121 static int
 30122 normal_char_height (struct font *font, int c)
 30123 {
 30124   int ascent, descent;
 30125 
 30126   normal_char_ascent_descent (font, c, &ascent, &descent);
 30127 
 30128   return ascent + descent;
 30129 }
 30130 
 30131 /* EXPORT for RIF:
 30132    Set *LEFT and *RIGHT to the left and right overhang of GLYPH on
 30133    frame F.  Overhangs of glyphs other than type CHAR_GLYPH are
 30134    assumed to be zero.  */
 30135 
 30136 void
 30137 gui_get_glyph_overhangs (struct glyph *glyph, struct frame *f, int *left, int *right)
 30138 {
 30139   *left = *right = 0;
 30140 
 30141   if (glyph->type == CHAR_GLYPH)
 30142     {
 30143       unsigned char2b;
 30144       struct face *face = get_glyph_face_and_encoding (f, glyph, &char2b);
 30145       if (face->font)
 30146         {
 30147           struct font_metrics *pcm = get_per_char_metric (face->font, &char2b);
 30148           if (pcm)
 30149             {
 30150               if (pcm->rbearing > pcm->width)
 30151                 *right = pcm->rbearing - pcm->width;
 30152               if (pcm->lbearing < 0)
 30153                 *left = -pcm->lbearing;
 30154             }
 30155         }
 30156     }
 30157   else if (glyph->type == COMPOSITE_GLYPH)
 30158     {
 30159       if (! glyph->u.cmp.automatic)
 30160         {
 30161           struct composition *cmp = composition_table[glyph->u.cmp.id];
 30162 
 30163           if (cmp->rbearing > cmp->pixel_width)
 30164             *right = cmp->rbearing - cmp->pixel_width;
 30165           if (cmp->lbearing < 0)
 30166             *left = - cmp->lbearing;
 30167         }
 30168       else
 30169         {
 30170           Lisp_Object gstring = composition_gstring_from_id (glyph->u.cmp.id);
 30171           struct font_metrics metrics;
 30172 
 30173           composition_gstring_width (gstring, glyph->slice.cmp.from,
 30174                                      glyph->slice.cmp.to + 1, &metrics);
 30175           if (metrics.rbearing > metrics.width)
 30176             *right = metrics.rbearing - metrics.width;
 30177           if (metrics.lbearing < 0)
 30178             *left = - metrics.lbearing;
 30179         }
 30180     }
 30181 }
 30182 
 30183 
 30184 /* Return the index of the first glyph preceding glyph string S that
 30185    is overwritten by S because of S's left overhang.  Value is -1
 30186    if no glyphs are overwritten.  */
 30187 
 30188 static int
 30189 left_overwritten (struct glyph_string *s)
 30190 {
 30191   int k;
 30192 
 30193   if (s->left_overhang)
 30194     {
 30195       int x = 0, i;
 30196       struct glyph *glyphs = s->row->glyphs[s->area];
 30197       int first = s->first_glyph - glyphs;
 30198 
 30199       for (i = first - 1; i >= 0 && x > -s->left_overhang; --i)
 30200         x -= glyphs[i].pixel_width;
 30201 
 30202       k = i + 1;
 30203     }
 30204   else
 30205     k = -1;
 30206 
 30207   return k;
 30208 }
 30209 
 30210 
 30211 /* Return the index of the first glyph preceding glyph string S that
 30212    is overwriting S because of its right overhang.  Value is -1 if no
 30213    glyph in front of S overwrites S.  */
 30214 
 30215 static int
 30216 left_overwriting (struct glyph_string *s)
 30217 {
 30218   int i, k, x;
 30219   struct glyph *glyphs = s->row->glyphs[s->area];
 30220   int first = s->first_glyph - glyphs;
 30221 
 30222   k = -1;
 30223   x = 0;
 30224   for (i = first - 1; i >= 0; --i)
 30225     {
 30226       int left, right;
 30227       gui_get_glyph_overhangs (glyphs + i, s->f, &left, &right);
 30228       if (x + right > 0)
 30229         k = i;
 30230       x -= glyphs[i].pixel_width;
 30231     }
 30232 
 30233   return k;
 30234 }
 30235 
 30236 
 30237 /* Return the index of the last glyph following glyph string S that is
 30238    overwritten by S because of S's right overhang.  Value is -1 if
 30239    no such glyph is found.  */
 30240 
 30241 static int
 30242 right_overwritten (struct glyph_string *s)
 30243 {
 30244   int k = -1;
 30245 
 30246   if (s->right_overhang)
 30247     {
 30248       int x = 0, i;
 30249       struct glyph *glyphs = s->row->glyphs[s->area];
 30250       int first = (s->first_glyph - glyphs
 30251                    + (s->first_glyph->type == COMPOSITE_GLYPH ? 1 : s->nchars));
 30252       int end = s->row->used[s->area];
 30253 
 30254       for (i = first; i < end && s->right_overhang > x; ++i)
 30255         x += glyphs[i].pixel_width;
 30256 
 30257       k = i;
 30258     }
 30259 
 30260   return k;
 30261 }
 30262 
 30263 
 30264 /* Return the index of the last glyph following glyph string S that
 30265    overwrites S because of its left overhang.  Value is negative
 30266    if no such glyph is found.  */
 30267 
 30268 static int
 30269 right_overwriting (struct glyph_string *s)
 30270 {
 30271   int i, k, x;
 30272   int end = s->row->used[s->area];
 30273   struct glyph *glyphs = s->row->glyphs[s->area];
 30274   int first = (s->first_glyph - glyphs
 30275                + (s->first_glyph->type == COMPOSITE_GLYPH ? 1 : s->nchars));
 30276 
 30277   k = -1;
 30278   x = 0;
 30279   for (i = first; i < end; ++i)
 30280     {
 30281       int left, right;
 30282       gui_get_glyph_overhangs (glyphs + i, s->f, &left, &right);
 30283       if (x - left < 0)
 30284         k = i;
 30285       x += glyphs[i].pixel_width;
 30286     }
 30287 
 30288   return k;
 30289 }
 30290 
 30291 
 30292 /* Set background width of glyph string S.  START is the index of the
 30293    first glyph following S.  LAST_X is the right-most x-position + 1
 30294    in the drawing area.
 30295 
 30296    If S->hl is DRAW_CURSOR, S->f is a window system frame, and the
 30297    cursor in S's window is currently inside mouse face, also update
 30298    S->width to take into account potentially differing :box
 30299    properties between the original face and the mouse face.  */
 30300 
 30301 static void
 30302 set_glyph_string_background_width (struct glyph_string *s, int start, int last_x)
 30303 {
 30304   /* If the face of this glyph string has to be drawn to the end of
 30305      the drawing area, set S->extends_to_end_of_line_p.  */
 30306 
 30307   if (start == s->row->used[s->area]
 30308       && ((s->row->fill_line_p
 30309            && (s->hl == DRAW_NORMAL_TEXT
 30310                || s->hl == DRAW_IMAGE_RAISED
 30311                || s->hl == DRAW_IMAGE_SUNKEN))
 30312           || s->hl == DRAW_MOUSE_FACE))
 30313     s->extends_to_end_of_line_p = true;
 30314 
 30315   /* If S extends its face to the end of the line, set its
 30316      background_width to the distance to the right edge of the drawing
 30317      area.  */
 30318   if (s->extends_to_end_of_line_p)
 30319     s->background_width = last_x - s->x + 1;
 30320   else
 30321     {
 30322       s->background_width = s->width;
 30323 #ifdef HAVE_WINDOW_SYSTEM
 30324       if (FRAME_WINDOW_P (s->f)
 30325           && s->hl == DRAW_CURSOR
 30326           && MATRIX_ROW (s->w->current_matrix,
 30327                          s->w->phys_cursor.vpos)->mouse_face_p
 30328           && cursor_in_mouse_face_p (s->w))
 30329         {
 30330           /* Adjust the background width of the glyph string, because
 30331              if the glyph's face has the :box attribute, its
 30332              pixel_width might be different when it's displayed in the
 30333              mouse-face, if that also has the :box attribute.  */
 30334           struct glyph *g = s->first_glyph;
 30335           struct face *regular_face = FACE_FROM_ID (s->f, g->face_id);
 30336           s->background_width +=
 30337             adjust_glyph_width_for_mouse_face (g, s->row, s->w,
 30338                                                regular_face, s->face);
 30339           /* S->width is probably worth adjusting here as well.  */
 30340           s->width = s->background_width;
 30341         }
 30342 #endif
 30343     }
 30344 }
 30345 
 30346 
 30347 /* Return glyph string that shares background with glyph string S and
 30348    whose `background_width' member has been set.  */
 30349 
 30350 static struct glyph_string *
 30351 glyph_string_containing_background_width (struct glyph_string *s)
 30352 {
 30353   if (s->cmp)
 30354     while (s->cmp_from)
 30355       s = s->prev;
 30356 
 30357   return s;
 30358 }
 30359 
 30360 
 30361 /* Compute overhangs and x-positions for glyph string S and its
 30362    predecessors, or successors.  X is the starting x-position for S.
 30363    BACKWARD_P means process predecessors.  */
 30364 
 30365 static void
 30366 compute_overhangs_and_x (struct glyph_string *s, int x, bool backward_p)
 30367 {
 30368   if (backward_p)
 30369     {
 30370       while (s)
 30371         {
 30372           if (FRAME_RIF (s->f)->compute_glyph_string_overhangs)
 30373             FRAME_RIF (s->f)->compute_glyph_string_overhangs (s);
 30374           if (!s->cmp || s->cmp_to == s->cmp->glyph_len)
 30375             x -= s->width;
 30376           s->x = x;
 30377           s = s->prev;
 30378         }
 30379     }
 30380   else
 30381     {
 30382       while (s)
 30383         {
 30384           if (FRAME_RIF (s->f)->compute_glyph_string_overhangs)
 30385             FRAME_RIF (s->f)->compute_glyph_string_overhangs (s);
 30386           s->x = x;
 30387           if (!s->cmp || s->cmp_to == s->cmp->glyph_len)
 30388             x += s->width;
 30389           s = s->next;
 30390         }
 30391     }
 30392 }
 30393 
 30394 
 30395 
 30396 /* The following macros are only called from draw_glyphs below.
 30397    They reference the following parameters of that function directly:
 30398      `w', `row', `area', and `overlap_p'
 30399    as well as the following local variables:
 30400      `s', `f', and `hdc' (in W32)  */
 30401 
 30402 #ifdef HAVE_NTGUI
 30403 /* On W32, silently add local `hdc' variable to argument list of
 30404    init_glyph_string.  */
 30405 #define INIT_GLYPH_STRING(s, char2b, w, row, area, start, hl) \
 30406   init_glyph_string (s, hdc, char2b, w, row, area, start, hl)
 30407 #else
 30408 #define INIT_GLYPH_STRING(s, char2b, w, row, area, start, hl) \
 30409   init_glyph_string (s, char2b, w, row, area, start, hl)
 30410 #endif
 30411 
 30412 /* Add a glyph string for a stretch glyph to the list of strings
 30413    between HEAD and TAIL.  START is the index of the stretch glyph in
 30414    row area AREA of glyph row ROW.  END is the index of the last glyph
 30415    in that glyph row area.  X is the current output position assigned
 30416    to the new glyph string constructed.  HL overrides that face of the
 30417    glyph; e.g. it is DRAW_CURSOR if a cursor has to be drawn.  LAST_X
 30418    is the right-most x-position of the drawing area.  */
 30419 
 30420 /* SunOS 4 bundled cc, barfed on continuations in the arg lists here
 30421    and below -- keep them on one line.  */
 30422 #define BUILD_STRETCH_GLYPH_STRING(START, END, HEAD, TAIL, HL, X, LAST_X)   \
 30423      do                                                                     \
 30424        {                                                                    \
 30425          s = alloca (sizeof *s);                                            \
 30426          INIT_GLYPH_STRING (s, NULL, w, row, area, START, HL);              \
 30427          START = fill_stretch_glyph_string (s, START, END);                 \
 30428          append_glyph_string (&HEAD, &TAIL, s);                             \
 30429          s->x = (X);                                                        \
 30430        }                                                                    \
 30431      while (false)
 30432 
 30433 
 30434 /* Add a glyph string for an image glyph to the list of strings
 30435    between HEAD and TAIL.  START is the index of the image glyph in
 30436    row area AREA of glyph row ROW.  END is the index of the last glyph
 30437    in that glyph row area.  X is the current output position assigned
 30438    to the new glyph string constructed.  HL overrides that face of the
 30439    glyph; e.g. it is DRAW_CURSOR if a cursor has to be drawn.  LAST_X
 30440    is the right-most x-position of the drawing area.  */
 30441 
 30442 #define BUILD_IMAGE_GLYPH_STRING(START, END, HEAD, TAIL, HL, X, LAST_X) \
 30443      do                                                                 \
 30444        {                                                                \
 30445          s = alloca (sizeof *s);                                        \
 30446          INIT_GLYPH_STRING (s, NULL, w, row, area, START, HL);          \
 30447          fill_image_glyph_string (s);                                   \
 30448          append_glyph_string (&HEAD, &TAIL, s);                         \
 30449          ++START;                                                       \
 30450          s->x = (X);                                                    \
 30451        }                                                                \
 30452      while (false)
 30453 
 30454 #ifndef HAVE_XWIDGETS
 30455 # define BUILD_XWIDGET_GLYPH_STRING(START, END, HEAD, TAIL, HL, X, LAST_X) \
 30456      eassume (false)
 30457 #else
 30458 # define BUILD_XWIDGET_GLYPH_STRING(START, END, HEAD, TAIL, HL, X, LAST_X) \
 30459      do                                                                 \
 30460        {                                                                \
 30461          s = alloca (sizeof *s);                                        \
 30462          INIT_GLYPH_STRING (s, NULL, w, row, area, START, HL);          \
 30463          fill_xwidget_glyph_string (s);                                 \
 30464          append_glyph_string (&(HEAD), &(TAIL), s);                     \
 30465          ++(START);                                                     \
 30466          s->x = (X);                                                    \
 30467        }                                                                \
 30468      while (false)
 30469 #endif
 30470 
 30471 /* Add a glyph string for a sequence of character glyphs to the list
 30472    of strings between HEAD and TAIL.  START is the index of the first
 30473    glyph in row area AREA of glyph row ROW that is part of the new
 30474    glyph string.  END is the index of the last glyph in that glyph row
 30475    area.  X is the current output position assigned to the new glyph
 30476    string constructed.  HL overrides that face of the glyph; e.g. it
 30477    is DRAW_CURSOR if a cursor has to be drawn.  LAST_X is the
 30478    right-most x-position of the drawing area.  */
 30479 
 30480 #define BUILD_CHAR_GLYPH_STRINGS(START, END, HEAD, TAIL, HL, X, LAST_X)    \
 30481      do                                                                    \
 30482        {                                                                   \
 30483          int face_id;                                                      \
 30484          unsigned *char2b;                                         \
 30485                                                                            \
 30486          face_id = (row)->glyphs[area][START].face_id;                     \
 30487                                                                            \
 30488          s = alloca (sizeof *s);                                           \
 30489          SAFE_NALLOCA (char2b, 1, (END) - (START));                        \
 30490          INIT_GLYPH_STRING (s, char2b, w, row, area, START, HL);           \
 30491          append_glyph_string (&HEAD, &TAIL, s);                            \
 30492          s->x = (X);                                                       \
 30493          START = fill_glyph_string (s, face_id, START, END, overlaps);     \
 30494        }                                                                   \
 30495      while (false)
 30496 
 30497 
 30498 /* Add a glyph string for a composite sequence to the list of strings
 30499    between HEAD and TAIL.  START is the index of the first glyph in
 30500    row area AREA of glyph row ROW that is part of the new glyph
 30501    string.  END is the index of the last glyph in that glyph row area.
 30502    X is the current output position assigned to the new glyph string
 30503    constructed.  HL overrides that face of the glyph; e.g. it is
 30504    DRAW_CURSOR if a cursor has to be drawn.  LAST_X is the right-most
 30505    x-position of the drawing area.  */
 30506 
 30507 #define BUILD_COMPOSITE_GLYPH_STRING(START, END, HEAD, TAIL, HL, X, LAST_X) \
 30508   do {                                                                      \
 30509     int face_id = (row)->glyphs[area][START].face_id;                       \
 30510     struct face *base_face = FACE_FROM_ID (f, face_id);             \
 30511     ptrdiff_t cmp_id = (row)->glyphs[area][START].u.cmp.id;                 \
 30512     struct composition *cmp = composition_table[cmp_id];                    \
 30513     unsigned *char2b;                                                       \
 30514     struct glyph_string *first_s = NULL;                                    \
 30515     int n;                                                                  \
 30516                                                                             \
 30517     SAFE_NALLOCA (char2b, 1, cmp->glyph_len);                               \
 30518                                                                             \
 30519     /* Make glyph_strings for each glyph sequence that is drawable by       \
 30520        the same face, and append them to HEAD/TAIL.  */                     \
 30521     for (n = 0; n < cmp->glyph_len;)                                        \
 30522       {                                                                     \
 30523         s = alloca (sizeof *s);                                             \
 30524         INIT_GLYPH_STRING (s, char2b, w, row, area, START, HL);             \
 30525         append_glyph_string (&(HEAD), &(TAIL), s);                          \
 30526         s->cmp = cmp;                                                       \
 30527         s->cmp_from = n;                                                    \
 30528         s->x = (X);                                                         \
 30529         if (n == 0)                                                         \
 30530           first_s = s;                                                      \
 30531         n = fill_composite_glyph_string (s, base_face, overlaps);           \
 30532       }                                                                     \
 30533                                                                             \
 30534     ++START;                                                                \
 30535     s = first_s;                                                            \
 30536   } while (false)
 30537 
 30538 
 30539 /* Add a glyph string for a glyph-string sequence to the list of strings
 30540    between HEAD and TAIL.  */
 30541 
 30542 #define BUILD_GSTRING_GLYPH_STRING(START, END, HEAD, TAIL, HL, X, LAST_X) \
 30543   do {                                                                    \
 30544     int face_id;                                                          \
 30545     unsigned *char2b;                                                     \
 30546     Lisp_Object gstring;                                                  \
 30547                                                                           \
 30548     face_id = (row)->glyphs[area][START].face_id;                         \
 30549     gstring = (composition_gstring_from_id                                \
 30550                ((row)->glyphs[area][START].u.cmp.id));                    \
 30551     s = alloca (sizeof *s);                                               \
 30552     SAFE_NALLOCA (char2b, 1, LGSTRING_GLYPH_LEN (gstring));               \
 30553     INIT_GLYPH_STRING (s, char2b, w, row, area, START, HL);               \
 30554     append_glyph_string (&(HEAD), &(TAIL), s);                            \
 30555     s->x = (X);                                                           \
 30556     START = fill_gstring_glyph_string (s, face_id, START, END, overlaps); \
 30557   } while (false)
 30558 
 30559 
 30560 /* Add a glyph string for a sequence of glyphless character's glyphs
 30561    to the list of strings between HEAD and TAIL.  The meanings of
 30562    arguments are the same as those of BUILD_CHAR_GLYPH_STRINGS.  */
 30563 
 30564 #define BUILD_GLYPHLESS_GLYPH_STRING(START, END, HEAD, TAIL, HL, X, LAST_X) \
 30565   do                                                                        \
 30566     {                                                                       \
 30567       int face_id;                                                          \
 30568                                                                             \
 30569       face_id = (row)->glyphs[area][START].face_id;                         \
 30570                                                                             \
 30571       s = alloca (sizeof *s);                                               \
 30572       INIT_GLYPH_STRING (s, NULL, w, row, area, START, HL);                 \
 30573       append_glyph_string (&HEAD, &TAIL, s);                                \
 30574       s->x = (X);                                                           \
 30575       START = fill_glyphless_glyph_string (s, face_id, START, END,          \
 30576                                            overlaps);                       \
 30577     }                                                                       \
 30578   while (false)
 30579 
 30580 
 30581 /* Build a list of glyph strings between HEAD and TAIL for the glyphs
 30582    of AREA of glyph row ROW on window W between indices START and END.
 30583    HL overrides the face for drawing glyph strings, e.g. it is
 30584    DRAW_CURSOR to draw a cursor.  X and LAST_X are start and end
 30585    x-positions of the drawing area.
 30586 
 30587    This is an ugly monster macro construct because we must use alloca
 30588    to allocate glyph strings (because draw_glyphs can be called
 30589    asynchronously).  */
 30590 
 30591 #define BUILD_GLYPH_STRINGS_1(START, END, HEAD, TAIL, HL, X, LAST_X)    \
 30592   do                                                                    \
 30593     {                                                                   \
 30594       HEAD = TAIL = NULL;                                               \
 30595       while (START < END)                                               \
 30596         {                                                               \
 30597           struct glyph *first_glyph = (row)->glyphs[area] + START;      \
 30598           switch (first_glyph->type)                                    \
 30599             {                                                           \
 30600             case CHAR_GLYPH:                                            \
 30601               BUILD_CHAR_GLYPH_STRINGS (START, END, HEAD, TAIL,         \
 30602                                         HL, X, LAST_X);                 \
 30603               break;                                                    \
 30604                                                                         \
 30605             case COMPOSITE_GLYPH:                                       \
 30606               if (first_glyph->u.cmp.automatic)                         \
 30607                 BUILD_GSTRING_GLYPH_STRING (START, END, HEAD, TAIL,     \
 30608                                             HL, X, LAST_X);             \
 30609               else                                                      \
 30610                 BUILD_COMPOSITE_GLYPH_STRING (START, END, HEAD, TAIL,   \
 30611                                               HL, X, LAST_X);           \
 30612               break;                                                    \
 30613                                                                         \
 30614             case STRETCH_GLYPH:                                         \
 30615               BUILD_STRETCH_GLYPH_STRING (START, END, HEAD, TAIL,       \
 30616                                           HL, X, LAST_X);               \
 30617               break;                                                    \
 30618                                                                         \
 30619             case IMAGE_GLYPH:                                           \
 30620               BUILD_IMAGE_GLYPH_STRING (START, END, HEAD, TAIL,         \
 30621                                         HL, X, LAST_X);                 \
 30622               break;
 30623 
 30624 #define BUILD_GLYPH_STRINGS_XW(START, END, HEAD, TAIL, HL, X, LAST_X)   \
 30625             case XWIDGET_GLYPH:                                         \
 30626               BUILD_XWIDGET_GLYPH_STRING (START, END, HEAD, TAIL,       \
 30627                                           HL, X, LAST_X);               \
 30628               break;
 30629 
 30630 #define BUILD_GLYPH_STRINGS_2(START, END, HEAD, TAIL, HL, X, LAST_X)    \
 30631             case GLYPHLESS_GLYPH:                                       \
 30632               BUILD_GLYPHLESS_GLYPH_STRING (START, END, HEAD, TAIL,     \
 30633                                             HL, X, LAST_X);             \
 30634               break;                                                    \
 30635                                                                         \
 30636             default:                                                    \
 30637               emacs_abort ();                                           \
 30638             }                                                           \
 30639                                                                         \
 30640           if (s)                                                        \
 30641             {                                                           \
 30642               set_glyph_string_background_width (s, START, LAST_X);     \
 30643               (X) += s->width;                                          \
 30644             }                                                           \
 30645         }                                                               \
 30646     } while (false)
 30647 
 30648 
 30649 #define BUILD_GLYPH_STRINGS(START, END, HEAD, TAIL, HL, X, LAST_X)      \
 30650     BUILD_GLYPH_STRINGS_1(START, END, HEAD, TAIL, HL, X, LAST_X)        \
 30651     BUILD_GLYPH_STRINGS_XW(START, END, HEAD, TAIL, HL, X, LAST_X)       \
 30652     BUILD_GLYPH_STRINGS_2(START, END, HEAD, TAIL, HL, X, LAST_X)
 30653 
 30654 
 30655 /* Draw glyphs between START and END in AREA of ROW on window W,
 30656    starting at x-position X.  X is relative to AREA in W.  HL is a
 30657    face-override with the following meaning:
 30658 
 30659    DRAW_NORMAL_TEXT     draw normally
 30660    DRAW_CURSOR          draw in cursor face
 30661    DRAW_MOUSE_FACE      draw in mouse face.
 30662    DRAW_INVERSE_VIDEO   draw in mode line face
 30663    DRAW_IMAGE_SUNKEN    draw an image with a sunken relief around it
 30664    DRAW_IMAGE_RAISED    draw an image with a raised relief around it
 30665 
 30666    If OVERLAPS is non-zero, draw only the foreground of characters and
 30667    clip to the physical height of ROW.  Non-zero value also defines
 30668    the overlapping part to be drawn:
 30669 
 30670    OVERLAPS_PRED                overlap with preceding rows
 30671    OVERLAPS_SUCC                overlap with succeeding rows
 30672    OVERLAPS_BOTH                overlap with both preceding/succeeding rows
 30673    OVERLAPS_ERASED_CURSOR       overlap with erased cursor area
 30674 
 30675    Value is the x-position reached, relative to AREA of W.  */
 30676 
 30677 static int
 30678 draw_glyphs (struct window *w, int x, struct glyph_row *row,
 30679              enum glyph_row_area area, ptrdiff_t start, ptrdiff_t end,
 30680              enum draw_glyphs_face hl, int overlaps)
 30681 {
 30682   struct glyph_string *head, *tail;
 30683   struct glyph_string *s;
 30684   struct glyph_string *clip_head = NULL, *clip_tail = NULL;
 30685   int i, j, x_reached, last_x, area_left = 0;
 30686   struct frame *f = XFRAME (WINDOW_FRAME (w));
 30687 
 30688   ALLOCATE_HDC (hdc, f);
 30689 
 30690   /* Let's rather be paranoid than getting a SEGV.  */
 30691   end = min (end, row->used[area]);
 30692   start = clip_to_bounds (0, start, end);
 30693 
 30694   /* Translate X to frame coordinates.  Set last_x to the right
 30695      end of the drawing area.  */
 30696   if (row->full_width_p)
 30697     {
 30698       /* X is relative to the left edge of W, without scroll bars
 30699          or fringes.  */
 30700       area_left = WINDOW_LEFT_EDGE_X (w);
 30701       last_x = (WINDOW_LEFT_EDGE_X (w) + WINDOW_PIXEL_WIDTH (w)
 30702                 - (row->mode_line_p ? WINDOW_RIGHT_DIVIDER_WIDTH (w) : 0));
 30703     }
 30704   else
 30705     {
 30706       area_left = window_box_left (w, area);
 30707       last_x = area_left + window_box_width (w, area);
 30708     }
 30709   x += area_left;
 30710 
 30711   /* Build a doubly-linked list of glyph_string structures between
 30712      head and tail from what we have to draw.  Note that the macro
 30713      BUILD_GLYPH_STRINGS will modify its start parameter.  That's
 30714      the reason we use a separate variable `i'.  */
 30715   i = start;
 30716   USE_SAFE_ALLOCA;
 30717   BUILD_GLYPH_STRINGS (i, end, head, tail, hl, x, last_x);
 30718   if (tail)
 30719     {
 30720       s = glyph_string_containing_background_width (tail);
 30721       x_reached = s->x + s->background_width;
 30722     }
 30723   else
 30724     x_reached = x;
 30725 
 30726   /* If there are any glyphs with lbearing < 0 or rbearing > width in
 30727      the row, redraw some glyphs in front or following the glyph
 30728      strings built above.  */
 30729   if (head && !overlaps && row->contains_overlapping_glyphs_p)
 30730     {
 30731       struct glyph_string *h, *t;
 30732       Mouse_HLInfo *hlinfo = MOUSE_HL_INFO (f);
 30733       int mouse_beg_col UNINIT, mouse_end_col UNINIT;
 30734       bool check_mouse_face = false;
 30735       int dummy_x = 0;
 30736 
 30737       /* If mouse highlighting is on, we may need to draw adjacent
 30738          glyphs using mouse-face highlighting.  */
 30739       if (area == TEXT_AREA && row->mouse_face_p
 30740           && hlinfo->mouse_face_beg_row >= 0
 30741           && hlinfo->mouse_face_end_row >= 0)
 30742         {
 30743           ptrdiff_t row_vpos = MATRIX_ROW_VPOS (row, w->current_matrix);
 30744 
 30745           if (row_vpos >= hlinfo->mouse_face_beg_row
 30746               && row_vpos <= hlinfo->mouse_face_end_row)
 30747             {
 30748               check_mouse_face = true;
 30749               mouse_beg_col = (row_vpos == hlinfo->mouse_face_beg_row)
 30750                 ? hlinfo->mouse_face_beg_col : 0;
 30751               mouse_end_col = (row_vpos == hlinfo->mouse_face_end_row)
 30752                 ? hlinfo->mouse_face_end_col
 30753                 : row->used[TEXT_AREA];
 30754             }
 30755         }
 30756 
 30757       /* Compute overhangs for all glyph strings.  */
 30758       if (FRAME_RIF (f)->compute_glyph_string_overhangs)
 30759         for (s = head; s; s = s->next)
 30760           FRAME_RIF (f)->compute_glyph_string_overhangs (s);
 30761 
 30762       /* Prepend glyph strings for glyphs in front of the first glyph
 30763          string that are overwritten because of the first glyph
 30764          string's left overhang.  The background of all strings
 30765          prepended must be drawn because the first glyph string
 30766          draws over it.  */
 30767       i = left_overwritten (head);
 30768       if (i >= 0)
 30769         {
 30770           enum draw_glyphs_face overlap_hl;
 30771 
 30772           /* If this row contains mouse highlighting, attempt to draw
 30773              the overlapped glyphs with the correct highlight.  This
 30774              code fails if the overlap encompasses more than one glyph
 30775              and mouse-highlight spans only some of these glyphs.
 30776              However, making it work perfectly involves a lot more
 30777              code, and I don't know if the pathological case occurs in
 30778              practice, so we'll stick to this for now.  --- cyd  */
 30779           if (check_mouse_face
 30780               && mouse_beg_col < start && mouse_end_col > i)
 30781             overlap_hl = DRAW_MOUSE_FACE;
 30782           else
 30783             overlap_hl = DRAW_NORMAL_TEXT;
 30784 
 30785           if (hl != overlap_hl)
 30786             clip_head = head;
 30787           j = i;
 30788           BUILD_GLYPH_STRINGS (j, start, h, t,
 30789                                overlap_hl, dummy_x, last_x);
 30790           start = i;
 30791           compute_overhangs_and_x (t, head->x, true);
 30792           prepend_glyph_string_lists (&head, &tail, h, t);
 30793           if (clip_head == NULL)
 30794             clip_head = head;
 30795         }
 30796 
 30797       /* Prepend glyph strings for glyphs in front of the first glyph
 30798          string that overwrite that glyph string because of their
 30799          right overhang.  For these strings, only the foreground must
 30800          be drawn, because it draws over the glyph string at `head'.
 30801          The background must not be drawn because this would overwrite
 30802          right overhangs of preceding glyphs for which no glyph
 30803          strings exist.  */
 30804       i = left_overwriting (head);
 30805       if (i >= 0)
 30806         {
 30807           enum draw_glyphs_face overlap_hl;
 30808 
 30809           if (check_mouse_face
 30810               && mouse_beg_col < start && mouse_end_col > i)
 30811             overlap_hl = DRAW_MOUSE_FACE;
 30812           else
 30813             overlap_hl = DRAW_NORMAL_TEXT;
 30814 
 30815           if (hl == overlap_hl || clip_head == NULL)
 30816             clip_head = head;
 30817           BUILD_GLYPH_STRINGS (i, start, h, t,
 30818                                overlap_hl, dummy_x, last_x);
 30819           for (s = h; s; s = s->next)
 30820             s->background_filled_p = true;
 30821           compute_overhangs_and_x (t, head->x, true);
 30822           prepend_glyph_string_lists (&head, &tail, h, t);
 30823         }
 30824 
 30825       /* Append glyphs strings for glyphs following the last glyph
 30826          string tail that are overwritten by tail.  The background of
 30827          these strings has to be drawn because tail's foreground draws
 30828          over it.  */
 30829       i = right_overwritten (tail);
 30830       if (i >= 0)
 30831         {
 30832           enum draw_glyphs_face overlap_hl;
 30833 
 30834           if (check_mouse_face
 30835               && mouse_beg_col < i && mouse_end_col > end)
 30836             overlap_hl = DRAW_MOUSE_FACE;
 30837           else
 30838             overlap_hl = DRAW_NORMAL_TEXT;
 30839 
 30840           if (hl != overlap_hl)
 30841             clip_tail = tail;
 30842           BUILD_GLYPH_STRINGS (end, i, h, t,
 30843                                overlap_hl, x, last_x);
 30844           /* Because BUILD_GLYPH_STRINGS updates the first argument,
 30845              we don't have `end = i;' here.  */
 30846           compute_overhangs_and_x (h, tail->x + tail->width, false);
 30847           append_glyph_string_lists (&head, &tail, h, t);
 30848           if (clip_tail == NULL)
 30849             clip_tail = tail;
 30850         }
 30851 
 30852       /* Append glyph strings for glyphs following the last glyph
 30853          string tail that overwrite tail.  The foreground of such
 30854          glyphs has to be drawn because it writes into the background
 30855          of tail.  The background must not be drawn because it could
 30856          paint over the foreground of following glyphs.  */
 30857       i = right_overwriting (tail);
 30858       if (i >= 0)
 30859         {
 30860           enum draw_glyphs_face overlap_hl;
 30861           if (check_mouse_face
 30862               && mouse_beg_col < i && mouse_end_col > end)
 30863             overlap_hl = DRAW_MOUSE_FACE;
 30864           else
 30865             overlap_hl = DRAW_NORMAL_TEXT;
 30866 
 30867           if (hl == overlap_hl || clip_tail == NULL)
 30868             clip_tail = tail;
 30869           i++;                  /* We must include the Ith glyph.  */
 30870           BUILD_GLYPH_STRINGS (end, i, h, t,
 30871                                overlap_hl, x, last_x);
 30872           for (s = h; s; s = s->next)
 30873             s->background_filled_p = true;
 30874           compute_overhangs_and_x (h, tail->x + tail->width, false);
 30875           append_glyph_string_lists (&head, &tail, h, t);
 30876         }
 30877       tail = glyph_string_containing_background_width (tail);
 30878       if (clip_tail)
 30879         clip_tail = glyph_string_containing_background_width (clip_tail);
 30880       if (clip_head || clip_tail)
 30881         for (s = head; s; s = s->next)
 30882           {
 30883             s->clip_head = clip_head;
 30884             s->clip_tail = clip_tail;
 30885           }
 30886     }
 30887 
 30888   /* Draw all strings.  */
 30889   for (s = head; s; s = s->next)
 30890     FRAME_RIF (f)->draw_glyph_string (s);
 30891 
 30892   /* When focus a sole frame and move horizontally, this clears on_p
 30893      causing a failure to erase prev cursor position. */
 30894   if (area == TEXT_AREA
 30895       && !row->full_width_p
 30896       /* When drawing overlapping rows, only the glyph strings'
 30897          foreground is drawn, which doesn't erase a cursor
 30898          completely. */
 30899       && !overlaps)
 30900     {
 30901       int x0 = clip_head ? clip_head->x : (head ? head->x : x);
 30902       int x1 = (clip_tail ? clip_tail->x + clip_tail->background_width
 30903                 : (tail ? tail->x + tail->background_width : x));
 30904       x0 -= area_left;
 30905       x1 -= area_left;
 30906 
 30907       notice_overwritten_cursor (w, TEXT_AREA, x0, x1,
 30908                                  row->y, MATRIX_ROW_BOTTOM_Y (row));
 30909     }
 30910 
 30911   /* Value is the x-position up to which drawn, relative to AREA of W.
 30912      This doesn't include parts drawn because of overhangs.  */
 30913   if (row->full_width_p)
 30914     x_reached = FRAME_TO_WINDOW_PIXEL_X (w, x_reached);
 30915   else
 30916     x_reached -= area_left;
 30917 
 30918   RELEASE_HDC (hdc, f);
 30919 
 30920   SAFE_FREE ();
 30921   return x_reached;
 30922 }
 30923 
 30924 /* Find the first glyph in the run of underlined glyphs preceding the
 30925    beginning of glyph string S, and return its font (which could be
 30926    NULL).  This is needed because that font determines the underline
 30927    position and thickness for the entire run of the underlined glyphs.
 30928    This function is called from the draw_glyph_string method of GUI
 30929    frame's redisplay interface (RIF) when it needs to draw in an
 30930    underlined face.  */
 30931 struct font *
 30932 font_for_underline_metrics (struct glyph_string *s)
 30933 {
 30934   struct glyph *g0 = s->row->glyphs[s->area], *g;
 30935 
 30936   for (g = s->first_glyph - 1; g >= g0; g--)
 30937     {
 30938       struct face *prev_face = FACE_FROM_ID (s->f, g->face_id);
 30939       if (!(prev_face && prev_face->underline != FACE_NO_UNDERLINE))
 30940         break;
 30941     }
 30942 
 30943   /* If preceding glyphs are not underlined, use the font of S.  */
 30944   if (g == s->first_glyph - 1)
 30945     return s->font;
 30946   else
 30947     {
 30948       /* Otherwise use the font of the last glyph we saw in the above
 30949          loop whose face had the underline_p flag set.  */
 30950       return FACE_FROM_ID (s->f, g[1].face_id)->font;
 30951     }
 30952 }
 30953 
 30954 /* Expand row matrix if too narrow.  Don't expand if area
 30955    is not present.  */
 30956 
 30957 #define IT_EXPAND_MATRIX_WIDTH(it, area)                \
 30958   {                                                     \
 30959     if (!it->f->fonts_changed                           \
 30960         && (it->glyph_row->glyphs[area]                 \
 30961             < it->glyph_row->glyphs[area + 1]))         \
 30962       {                                                 \
 30963         it->w->ncols_scale_factor++;                    \
 30964         it->f->fonts_changed = true;                    \
 30965       }                                                 \
 30966   }
 30967 
 30968 /* Store one glyph for IT->char_to_display in IT->glyph_row.
 30969    Called from gui_produce_glyphs when IT->glyph_row is non-null.  */
 30970 
 30971 static void
 30972 append_glyph (struct it *it)
 30973 {
 30974   struct glyph *glyph;
 30975   enum glyph_row_area area = it->area;
 30976 
 30977   eassert (it->glyph_row);
 30978   eassert (it->char_to_display != '\n' && it->char_to_display != '\t');
 30979 
 30980   glyph = it->glyph_row->glyphs[area] + it->glyph_row->used[area];
 30981   if (glyph < it->glyph_row->glyphs[area + 1])
 30982     {
 30983       /* If the glyph row is reversed, we need to prepend the glyph
 30984          rather than append it.  */
 30985       if (it->glyph_row->reversed_p && area == TEXT_AREA)
 30986         {
 30987           struct glyph *g;
 30988 
 30989           /* Make room for the additional glyph.  */
 30990           for (g = glyph - 1; g >= it->glyph_row->glyphs[area]; g--)
 30991             g[1] = *g;
 30992           glyph = it->glyph_row->glyphs[area];
 30993         }
 30994       glyph->charpos = CHARPOS (it->position);
 30995       glyph->object = it->object;
 30996       if (it->pixel_width > 0)
 30997         {
 30998           eassert (it->pixel_width <= SHRT_MAX);
 30999           glyph->pixel_width = it->pixel_width;
 31000           glyph->padding_p = false;
 31001         }
 31002       else
 31003         {
 31004           /* Assure at least 1-pixel width.  Otherwise, cursor can't
 31005              be displayed correctly.  */
 31006           glyph->pixel_width = 1;
 31007           glyph->padding_p = true;
 31008         }
 31009       glyph->ascent = it->ascent;
 31010       glyph->descent = it->descent;
 31011       glyph->voffset = it->voffset;
 31012       glyph->type = CHAR_GLYPH;
 31013       glyph->avoid_cursor_p = it->avoid_cursor_p;
 31014       glyph->multibyte_p = it->multibyte_p;
 31015       if (it->glyph_row->reversed_p && area == TEXT_AREA)
 31016         {
 31017           /* In R2L rows, the left and the right box edges need to be
 31018              drawn in reverse direction.  */
 31019           glyph->right_box_line_p = it->start_of_box_run_p;
 31020           glyph->left_box_line_p = it->end_of_box_run_p;
 31021         }
 31022       else
 31023         {
 31024           glyph->left_box_line_p = it->start_of_box_run_p;
 31025           glyph->right_box_line_p = it->end_of_box_run_p;
 31026         }
 31027       glyph->overlaps_vertically_p = (it->phys_ascent > it->ascent
 31028                                       || it->phys_descent > it->descent);
 31029       glyph->glyph_not_available_p = it->glyph_not_available_p;
 31030       glyph->face_id = it->face_id;
 31031       glyph->u.ch = it->char_to_display;
 31032       glyph->slice.img = null_glyph_slice;
 31033       glyph->font_type = FONT_TYPE_UNKNOWN;
 31034       if (it->bidi_p)
 31035         {
 31036           glyph->resolved_level = it->bidi_it.resolved_level;
 31037           eassert ((it->bidi_it.type & 7) == it->bidi_it.type);
 31038           glyph->bidi_type = it->bidi_it.type;
 31039         }
 31040       else
 31041         {
 31042           glyph->resolved_level = 0;
 31043           glyph->bidi_type = UNKNOWN_BT;
 31044         }
 31045       ++it->glyph_row->used[area];
 31046     }
 31047   else
 31048     IT_EXPAND_MATRIX_WIDTH (it, area);
 31049 }
 31050 
 31051 /* Store one glyph for the composition IT->cmp_it.id in IT->glyph_row.
 31052    Called from gui_produce_glyphs when IT->glyph_row is non-null.  */
 31053 
 31054 static void
 31055 append_composite_glyph (struct it *it)
 31056 {
 31057   struct glyph *glyph;
 31058   enum glyph_row_area area = it->area;
 31059 
 31060   eassert (it->glyph_row);
 31061 
 31062   glyph = it->glyph_row->glyphs[area] + it->glyph_row->used[area];
 31063   if (glyph < it->glyph_row->glyphs[area + 1])
 31064     {
 31065       /* If the glyph row is reversed, we need to prepend the glyph
 31066          rather than append it.  */
 31067       if (it->glyph_row->reversed_p && it->area == TEXT_AREA)
 31068         {
 31069           struct glyph *g;
 31070 
 31071           /* Make room for the new glyph.  */
 31072           for (g = glyph - 1; g >= it->glyph_row->glyphs[it->area]; g--)
 31073             g[1] = *g;
 31074           glyph = it->glyph_row->glyphs[it->area];
 31075         }
 31076       glyph->charpos = it->cmp_it.charpos;
 31077       glyph->object = it->object;
 31078       eassert (it->pixel_width <= SHRT_MAX);
 31079       glyph->pixel_width = it->pixel_width;
 31080       glyph->ascent = it->ascent;
 31081       glyph->descent = it->descent;
 31082       glyph->voffset = it->voffset;
 31083       glyph->type = COMPOSITE_GLYPH;
 31084       if (it->cmp_it.ch < 0)
 31085         {
 31086           glyph->u.cmp.automatic = false;
 31087           glyph->u.cmp.id = it->cmp_it.id;
 31088           glyph->slice.cmp.from = glyph->slice.cmp.to = 0;
 31089         }
 31090       else
 31091         {
 31092           glyph->u.cmp.automatic = true;
 31093           glyph->u.cmp.id = it->cmp_it.id;
 31094           glyph->slice.cmp.from = it->cmp_it.from;
 31095           glyph->slice.cmp.to = it->cmp_it.to - 1;
 31096         }
 31097       glyph->avoid_cursor_p = it->avoid_cursor_p;
 31098       glyph->multibyte_p = it->multibyte_p;
 31099       if (it->glyph_row->reversed_p && area == TEXT_AREA)
 31100         {
 31101           /* In R2L rows, the left and the right box edges need to be
 31102              drawn in reverse direction.  */
 31103           glyph->right_box_line_p = it->start_of_box_run_p;
 31104           glyph->left_box_line_p = it->end_of_box_run_p;
 31105         }
 31106       else
 31107         {
 31108           glyph->left_box_line_p = it->start_of_box_run_p;
 31109           glyph->right_box_line_p = it->end_of_box_run_p;
 31110         }
 31111       glyph->overlaps_vertically_p = (it->phys_ascent > it->ascent
 31112                                       || it->phys_descent > it->descent);
 31113       glyph->padding_p = false;
 31114       glyph->glyph_not_available_p = it->glyph_not_available_p;
 31115       glyph->face_id = it->face_id;
 31116       glyph->font_type = FONT_TYPE_UNKNOWN;
 31117       if (it->bidi_p)
 31118         {
 31119           glyph->resolved_level = it->bidi_it.resolved_level;
 31120           eassert ((it->bidi_it.type & 7) == it->bidi_it.type);
 31121           glyph->bidi_type = it->bidi_it.type;
 31122         }
 31123       ++it->glyph_row->used[area];
 31124     }
 31125   else
 31126     IT_EXPAND_MATRIX_WIDTH (it, area);
 31127 }
 31128 
 31129 
 31130 /* Change IT->ascent and IT->height according to the setting of
 31131    IT->voffset.  */
 31132 
 31133 static void
 31134 take_vertical_position_into_account (struct it *it)
 31135 {
 31136   if (it->voffset)
 31137     {
 31138       if (it->voffset < 0)
 31139         /* Increase the ascent so that we can display the text higher
 31140            in the line.  */
 31141         it->ascent -= it->voffset;
 31142       else
 31143         /* Increase the descent so that we can display the text lower
 31144            in the line.  */
 31145         it->descent += it->voffset;
 31146     }
 31147 }
 31148 
 31149 
 31150 /* Produce glyphs/get display metrics for the image IT is loaded with.
 31151    See the description of struct display_iterator in dispextern.h for
 31152    an overview of struct display_iterator.  */
 31153 
 31154 static void
 31155 produce_image_glyph (struct it *it)
 31156 {
 31157   struct image *img;
 31158   struct face *face;
 31159   int glyph_ascent, crop;
 31160   struct glyph_slice slice;
 31161 
 31162   eassert (it->what == IT_IMAGE);
 31163 
 31164   face = FACE_FROM_ID (it->f, it->face_id);
 31165   /* Make sure X resources of the face is loaded.  */
 31166   prepare_face_for_display (it->f, face);
 31167 
 31168   if (it->image_id < 0)
 31169     {
 31170       /* Fringe bitmap.  */
 31171       it->ascent = it->phys_ascent = 0;
 31172       it->descent = it->phys_descent = 0;
 31173       it->pixel_width = 0;
 31174       it->nglyphs = 0;
 31175       return;
 31176     }
 31177 
 31178   img = IMAGE_FROM_ID (it->f, it->image_id);
 31179   /* Make sure X resources of the image is loaded.  */
 31180   prepare_image_for_display (it->f, img);
 31181 
 31182   slice.x = slice.y = 0;
 31183   slice.width = img->width;
 31184   slice.height = img->height;
 31185 
 31186   if (FIXNUMP (it->slice.x))
 31187     slice.x = XFIXNUM (it->slice.x);
 31188   else if (FLOATP (it->slice.x))
 31189     slice.x = XFLOAT_DATA (it->slice.x) * img->width;
 31190 
 31191   if (FIXNUMP (it->slice.y))
 31192     slice.y = XFIXNUM (it->slice.y);
 31193   else if (FLOATP (it->slice.y))
 31194     slice.y = XFLOAT_DATA (it->slice.y) * img->height;
 31195 
 31196   if (FIXNUMP (it->slice.width))
 31197     slice.width = XFIXNUM (it->slice.width);
 31198   else if (FLOATP (it->slice.width))
 31199     slice.width = XFLOAT_DATA (it->slice.width) * img->width;
 31200 
 31201   if (FIXNUMP (it->slice.height))
 31202     slice.height = XFIXNUM (it->slice.height);
 31203   else if (FLOATP (it->slice.height))
 31204     slice.height = XFLOAT_DATA (it->slice.height) * img->height;
 31205 
 31206   if (slice.x >= img->width)
 31207     slice.x = img->width;
 31208   if (slice.y >= img->height)
 31209     slice.y = img->height;
 31210   if (slice.x + slice.width >= img->width)
 31211     slice.width = img->width - slice.x;
 31212   if (slice.y + slice.height > img->height)
 31213     slice.height = img->height - slice.y;
 31214 
 31215   if (slice.width == 0 || slice.height == 0)
 31216     return;
 31217 
 31218   it->ascent = it->phys_ascent = glyph_ascent = image_ascent (img, face, &slice);
 31219 
 31220   it->descent = slice.height - glyph_ascent;
 31221   if (slice.y == 0)
 31222     it->descent += img->vmargin;
 31223   if (slice.y + slice.height == img->height)
 31224     it->descent += img->vmargin;
 31225   it->phys_descent = it->descent;
 31226 
 31227   it->pixel_width = slice.width;
 31228   if (slice.x == 0)
 31229     it->pixel_width += img->hmargin;
 31230   if (slice.x + slice.width == img->width)
 31231     it->pixel_width += img->hmargin;
 31232 
 31233   /* It's quite possible for images to have an ascent greater than
 31234      their height, so don't get confused in that case.  */
 31235   if (it->descent < 0)
 31236     it->descent = 0;
 31237 
 31238   it->nglyphs = 1;
 31239 
 31240   if (face->box != FACE_NO_BOX)
 31241     {
 31242       /* If you change the logic here, please change it in
 31243          get_cursor_offset_for_mouse_face as well. */
 31244       if (face->box_horizontal_line_width > 0)
 31245         {
 31246           if (slice.y == 0)
 31247             it->ascent += face->box_horizontal_line_width;
 31248           if (slice.y + slice.height == img->height)
 31249             it->descent += face->box_horizontal_line_width;
 31250         }
 31251 
 31252       if (face->box_vertical_line_width > 0)
 31253         {
 31254           if (it->start_of_box_run_p && slice.x == 0)
 31255             it->pixel_width += face->box_vertical_line_width;
 31256           if (it->end_of_box_run_p && slice.x + slice.width == img->width)
 31257             it->pixel_width += face->box_vertical_line_width;
 31258         }
 31259     }
 31260 
 31261   take_vertical_position_into_account (it);
 31262 
 31263   /* Automatically crop wide image glyphs at right edge so we can
 31264      draw the cursor on same display row.  */
 31265   if ((crop = it->pixel_width - (it->last_visible_x - it->current_x), crop > 0)
 31266       && (it->hpos == 0 || it->pixel_width > it->last_visible_x / 4))
 31267     {
 31268       it->pixel_width -= crop;
 31269       slice.width -= crop;
 31270     }
 31271 
 31272   if (it->glyph_row)
 31273     {
 31274       struct glyph *glyph;
 31275       enum glyph_row_area area = it->area;
 31276 
 31277       glyph = it->glyph_row->glyphs[area] + it->glyph_row->used[area];
 31278       if (it->glyph_row->reversed_p)
 31279         {
 31280           struct glyph *g;
 31281 
 31282           /* Make room for the new glyph.  */
 31283           for (g = glyph - 1; g >= it->glyph_row->glyphs[it->area]; g--)
 31284             g[1] = *g;
 31285           glyph = it->glyph_row->glyphs[it->area];
 31286         }
 31287       if (glyph < it->glyph_row->glyphs[area + 1])
 31288         {
 31289           glyph->charpos = CHARPOS (it->position);
 31290           glyph->object = it->object;
 31291           glyph->pixel_width = clip_to_bounds (-1, it->pixel_width, SHRT_MAX);
 31292           glyph->ascent = glyph_ascent;
 31293           glyph->descent = it->descent;
 31294           glyph->voffset = it->voffset;
 31295           glyph->type = IMAGE_GLYPH;
 31296           glyph->avoid_cursor_p = it->avoid_cursor_p;
 31297           glyph->multibyte_p = it->multibyte_p;
 31298           if (it->glyph_row->reversed_p && area == TEXT_AREA)
 31299             {
 31300               /* In R2L rows, the left and the right box edges need to be
 31301                  drawn in reverse direction.  */
 31302               glyph->right_box_line_p = it->start_of_box_run_p;
 31303               glyph->left_box_line_p = it->end_of_box_run_p;
 31304             }
 31305           else
 31306             {
 31307               glyph->left_box_line_p = it->start_of_box_run_p;
 31308               glyph->right_box_line_p = it->end_of_box_run_p;
 31309             }
 31310           glyph->overlaps_vertically_p = false;
 31311           glyph->padding_p = false;
 31312           glyph->glyph_not_available_p = false;
 31313           glyph->face_id = it->face_id;
 31314           glyph->u.img_id = img->id;
 31315           glyph->slice.img = slice;
 31316           glyph->font_type = FONT_TYPE_UNKNOWN;
 31317           if (it->bidi_p)
 31318             {
 31319               glyph->resolved_level = it->bidi_it.resolved_level;
 31320               eassert ((it->bidi_it.type & 7) == it->bidi_it.type);
 31321               glyph->bidi_type = it->bidi_it.type;
 31322             }
 31323           ++it->glyph_row->used[area];
 31324         }
 31325       else
 31326         IT_EXPAND_MATRIX_WIDTH (it, area);
 31327     }
 31328 }
 31329 
 31330 static void
 31331 produce_xwidget_glyph (struct it *it)
 31332 {
 31333 #ifdef HAVE_XWIDGETS
 31334   struct xwidget *xw;
 31335   int glyph_ascent, crop;
 31336   eassert (it->what == IT_XWIDGET);
 31337 
 31338   struct face *face = FACE_FROM_ID (it->f, it->face_id);
 31339   /* Make sure X resources of the face is loaded.  */
 31340   prepare_face_for_display (it->f, face);
 31341 
 31342   xw = it->xwidget;
 31343   it->ascent = it->phys_ascent = glyph_ascent = xw->height/2;
 31344   it->descent = xw->height/2;
 31345   it->phys_descent = it->descent;
 31346   it->pixel_width = xw->width;
 31347   /* It's quite possible for images to have an ascent greater than
 31348      their height, so don't get confused in that case.  */
 31349   if (it->descent < 0)
 31350     it->descent = 0;
 31351 
 31352   it->nglyphs = 1;
 31353 
 31354   if (face->box != FACE_NO_BOX)
 31355     {
 31356       if (face->box_horizontal_line_width > 0)
 31357         {
 31358           it->ascent += face->box_horizontal_line_width;
 31359           it->descent += face->box_horizontal_line_width;
 31360         }
 31361 
 31362       if (face->box_vertical_line_width > 0)
 31363         {
 31364           if (it->start_of_box_run_p)
 31365             it->pixel_width += face->box_vertical_line_width;
 31366           it->pixel_width += face->box_vertical_line_width;
 31367         }
 31368     }
 31369 
 31370   take_vertical_position_into_account (it);
 31371 
 31372   /* Automatically crop wide image glyphs at right edge so we can
 31373      draw the cursor on same display row.  */
 31374   crop = it->pixel_width - (it->last_visible_x - it->current_x);
 31375   if (crop > 0 && (it->hpos == 0 || it->pixel_width > it->last_visible_x / 4))
 31376     it->pixel_width -= crop;
 31377 
 31378   if (it->glyph_row)
 31379     {
 31380       enum glyph_row_area area = it->area;
 31381       struct glyph *glyph
 31382         = it->glyph_row->glyphs[area] + it->glyph_row->used[area];
 31383 
 31384       if (it->glyph_row->reversed_p)
 31385         {
 31386           struct glyph *g;
 31387 
 31388           /* Make room for the new glyph.  */
 31389           for (g = glyph - 1; g >= it->glyph_row->glyphs[it->area]; g--)
 31390             g[1] = *g;
 31391           glyph = it->glyph_row->glyphs[it->area];
 31392         }
 31393       if (glyph < it->glyph_row->glyphs[area + 1])
 31394         {
 31395           glyph->charpos = CHARPOS (it->position);
 31396           glyph->object = it->object;
 31397           glyph->pixel_width = clip_to_bounds (-1, it->pixel_width, SHRT_MAX);
 31398           glyph->ascent = glyph_ascent;
 31399           glyph->descent = it->descent;
 31400           glyph->voffset = it->voffset;
 31401           glyph->type = XWIDGET_GLYPH;
 31402           glyph->avoid_cursor_p = it->avoid_cursor_p;
 31403           glyph->multibyte_p = it->multibyte_p;
 31404           if (it->glyph_row->reversed_p && area == TEXT_AREA)
 31405             {
 31406               /* In R2L rows, the left and the right box edges need to be
 31407                  drawn in reverse direction.  */
 31408               glyph->right_box_line_p = it->start_of_box_run_p;
 31409               glyph->left_box_line_p = it->end_of_box_run_p;
 31410             }
 31411           else
 31412             {
 31413               glyph->left_box_line_p = it->start_of_box_run_p;
 31414               glyph->right_box_line_p = it->end_of_box_run_p;
 31415             }
 31416           glyph->overlaps_vertically_p = 0;
 31417           glyph->padding_p = 0;
 31418           glyph->glyph_not_available_p = 0;
 31419           glyph->face_id = it->face_id;
 31420           glyph->u.xwidget = it->xwidget->xwidget_id;
 31421           glyph->font_type = FONT_TYPE_UNKNOWN;
 31422           if (it->bidi_p)
 31423             {
 31424               glyph->resolved_level = it->bidi_it.resolved_level;
 31425               eassert ((it->bidi_it.type & 7) == it->bidi_it.type);
 31426               glyph->bidi_type = it->bidi_it.type;
 31427             }
 31428           ++it->glyph_row->used[area];
 31429         }
 31430       else
 31431         IT_EXPAND_MATRIX_WIDTH (it, area);
 31432     }
 31433 #endif
 31434 }
 31435 
 31436 /* Append a stretch glyph to IT->glyph_row.  OBJECT is the source
 31437    of the glyph, WIDTH and HEIGHT are the width and height of the
 31438    stretch.  ASCENT is the ascent of the glyph (0 <= ASCENT <= HEIGHT).  */
 31439 
 31440 static void
 31441 append_stretch_glyph (struct it *it, Lisp_Object object,
 31442                       int width, int height, int ascent)
 31443 {
 31444   struct glyph *glyph;
 31445   enum glyph_row_area area = it->area;
 31446 
 31447   eassert (ascent >= 0 && ascent <= height);
 31448 
 31449   glyph = it->glyph_row->glyphs[area] + it->glyph_row->used[area];
 31450   if (glyph < it->glyph_row->glyphs[area + 1])
 31451     {
 31452       /* If the glyph row is reversed, we need to prepend the glyph
 31453          rather than append it.  */
 31454       if (it->glyph_row->reversed_p && area == TEXT_AREA)
 31455         {
 31456           struct glyph *g;
 31457 
 31458           /* Make room for the additional glyph.  */
 31459           for (g = glyph - 1; g >= it->glyph_row->glyphs[area]; g--)
 31460             g[1] = *g;
 31461           glyph = it->glyph_row->glyphs[area];
 31462 
 31463           /* Decrease the width of the first glyph of the row that
 31464              begins before first_visible_x (e.g., due to hscroll).
 31465              This is so the overall width of the row becomes smaller
 31466              by the scroll amount, and the stretch glyph appended by
 31467              extend_face_to_end_of_line will be wider, to shift the
 31468              row glyphs to the right.  (In L2R rows, the corresponding
 31469              left-shift effect is accomplished by setting row->x to a
 31470              negative value, which won't work with R2L rows.)
 31471 
 31472              This must leave us with a positive value of WIDTH, since
 31473              otherwise the call to move_it_in_display_line_to at the
 31474              beginning of display_line would have got past the entire
 31475              first glyph, and then it->current_x would have been
 31476              greater or equal to it->first_visible_x.  */
 31477           if (it->current_x < it->first_visible_x)
 31478             width -= it->first_visible_x - it->current_x;
 31479           eassert (width > 0);
 31480         }
 31481       glyph->charpos = CHARPOS (it->position);
 31482       glyph->object = object;
 31483       /* FIXME: It would be better to use TYPE_MAX here, but
 31484          __typeof__ is not portable enough...  */
 31485       glyph->pixel_width = clip_to_bounds (-1, width, SHRT_MAX);
 31486       glyph->ascent = ascent;
 31487       glyph->descent = height - ascent;
 31488       glyph->voffset = it->voffset;
 31489       glyph->type = STRETCH_GLYPH;
 31490       glyph->avoid_cursor_p = it->avoid_cursor_p;
 31491       glyph->multibyte_p = it->multibyte_p;
 31492       if (it->glyph_row->reversed_p && area == TEXT_AREA)
 31493         {
 31494           /* In R2L rows, the left and the right box edges need to be
 31495              drawn in reverse direction.  */
 31496           glyph->right_box_line_p = it->start_of_box_run_p;
 31497           glyph->left_box_line_p = it->end_of_box_run_p;
 31498         }
 31499       else
 31500         {
 31501           glyph->left_box_line_p = it->start_of_box_run_p;
 31502           glyph->right_box_line_p = it->end_of_box_run_p;
 31503         }
 31504       glyph->overlaps_vertically_p = false;
 31505       glyph->padding_p = false;
 31506       glyph->glyph_not_available_p = false;
 31507       glyph->face_id = it->face_id;
 31508       glyph->u.stretch.ascent = ascent;
 31509       glyph->u.stretch.height = height;
 31510       glyph->slice.img = null_glyph_slice;
 31511       glyph->font_type = FONT_TYPE_UNKNOWN;
 31512       if (it->bidi_p)
 31513         {
 31514           glyph->resolved_level = it->bidi_it.resolved_level;
 31515           eassert ((it->bidi_it.type & 7) == it->bidi_it.type);
 31516           glyph->bidi_type = it->bidi_it.type;
 31517         }
 31518       else
 31519         {
 31520           glyph->resolved_level = 0;
 31521           glyph->bidi_type = UNKNOWN_BT;
 31522         }
 31523       ++it->glyph_row->used[area];
 31524     }
 31525   else
 31526     IT_EXPAND_MATRIX_WIDTH (it, area);
 31527 }
 31528 
 31529 #endif  /* HAVE_WINDOW_SYSTEM */
 31530 
 31531 /* Produce a stretch glyph for iterator IT.  IT->object is the value
 31532    of the display property.  The value must be a list of the form
 31533    `(space KEYWORD VALUE ...)' with the following KEYWORD/VALUE pairs
 31534    being recognized:
 31535 
 31536    1. `:width WIDTH' specifies that the space should be WIDTH *
 31537    canonical char width wide.  WIDTH may be an integer or floating
 31538    point number.
 31539 
 31540    2. `:relative-width FACTOR' specifies that the width of the stretch
 31541    should be computed from the width of the first character having the
 31542    `display' property, and should be FACTOR times that width.
 31543 
 31544    3. `:align-to HPOS' specifies that the space should be wide enough
 31545    to reach HPOS, a value in canonical character units.
 31546 
 31547    Exactly one of the above pairs must be present.
 31548 
 31549    4. `:height HEIGHT' specifies that the height of the stretch produced
 31550    should be HEIGHT, measured in canonical character units.
 31551 
 31552    5. `:relative-height FACTOR' specifies that the height of the
 31553    stretch should be FACTOR times the height of the characters having
 31554    the display property.
 31555 
 31556    Either none or exactly one of 4 or 5 must be present.
 31557 
 31558    6. `:ascent ASCENT'  specifies that ASCENT percent of the height
 31559    of the stretch should be used for the ascent of the stretch.
 31560    ASCENT must be in the range 0 <= ASCENT <= 100.  */
 31561 
 31562 void
 31563 produce_stretch_glyph (struct it *it)
 31564 {
 31565   /* (space :width WIDTH :height HEIGHT ...)  */
 31566   Lisp_Object prop, plist;
 31567   int width = 0, height = 0, align_to = -1;
 31568   bool zero_width_ok_p = false;
 31569   double tem;
 31570   struct font *font = NULL;
 31571 
 31572 #ifdef HAVE_WINDOW_SYSTEM
 31573   int ascent = 0;
 31574   bool zero_height_ok_p = false;
 31575   struct face *face = NULL;     /* shut up GCC's -Wmaybe-uninitialized */
 31576 
 31577   if (FRAME_WINDOW_P (it->f))
 31578     {
 31579       face = FACE_FROM_ID (it->f, it->face_id);
 31580       font = face->font ? face->font : FRAME_FONT (it->f);
 31581       prepare_face_for_display (it->f, face);
 31582     }
 31583 #endif
 31584 
 31585   /* List should start with `space'.  */
 31586   eassert (CONSP (it->object) && EQ (XCAR (it->object), Qspace));
 31587   plist = XCDR (it->object);
 31588 
 31589   /* Compute the width of the stretch.  */
 31590   if ((prop = plist_get (plist, QCwidth), !NILP (prop))
 31591       && calc_pixel_width_or_height (&tem, it, prop, font, true, NULL))
 31592     {
 31593       /* Absolute width `:width WIDTH' specified and valid.  */
 31594       zero_width_ok_p = true;
 31595       width = (int)tem;
 31596     }
 31597   else if (prop = plist_get (plist, QCrelative_width), NUMVAL (prop) > 0)
 31598     {
 31599       /* Relative width `:relative-width FACTOR' specified and valid.
 31600          Compute the width of the characters having this `display'
 31601          property.  */
 31602       struct it it2;
 31603       Lisp_Object object =
 31604         it->sp > 0 ? it->stack[it->sp - 1].string : it->string;
 31605       unsigned char *p = (STRINGP (object)
 31606                           ? SDATA (object) + IT_STRING_BYTEPOS (*it)
 31607                           : BYTE_POS_ADDR (IT_BYTEPOS (*it)));
 31608       bool multibyte_p =
 31609         STRINGP (object) ? STRING_MULTIBYTE (object) : it->multibyte_p;
 31610 
 31611       it2 = *it;
 31612       if (multibyte_p)
 31613         {
 31614           it2.c = it2.char_to_display = string_char_and_length (p, &it2.len);
 31615 #ifdef HAVE_WINDOW_SYSTEM
 31616           if (FRAME_WINDOW_P (it->f) && ! ASCII_CHAR_P (it2.c))
 31617             it2.face_id = FACE_FOR_CHAR (it->f, face, it2.c,
 31618                                          IT_CHARPOS (*it),
 31619                                          STRINGP (object)? object : Qnil);
 31620 #endif
 31621         }
 31622       else
 31623         {
 31624           it2.c = it2.char_to_display = *p, it2.len = 1;
 31625           if (! ASCII_CHAR_P (it2.c))
 31626             it2.char_to_display = BYTE8_TO_CHAR (it2.c);
 31627         }
 31628 
 31629       it2.glyph_row = NULL;
 31630       it2.what = IT_CHARACTER;
 31631       PRODUCE_GLYPHS (&it2);
 31632       width = NUMVAL (prop) * it2.pixel_width;
 31633     }
 31634   else if ((prop = plist_get (plist, QCalign_to), !NILP (prop))
 31635            && calc_pixel_width_or_height (&tem, it, prop, font, true,
 31636                                           &align_to))
 31637     {
 31638       int x = it->current_x + it->continuation_lines_width;
 31639       int x0 = x;
 31640       /* Adjust for line numbers, if needed.   */
 31641       if (!NILP (Vdisplay_line_numbers) && it->line_number_produced_p)
 31642         {
 31643           x -= it->lnum_pixel_width;
 31644           /* Restore the original width, if required.  */
 31645           if (x + it->stretch_adjust >= it->first_visible_x)
 31646             x += it->stretch_adjust;
 31647         }
 31648 
 31649       if (it->glyph_row == NULL || !it->glyph_row->mode_line_p)
 31650         align_to = (align_to < 0
 31651                     ? 0
 31652                     : align_to - window_box_left_offset (it->w, TEXT_AREA));
 31653       else if (align_to < 0)
 31654         align_to = window_box_left_offset (it->w, TEXT_AREA);
 31655       width = max (0, (int)tem + align_to - x);
 31656 
 31657       int next_x = x + width;
 31658       if (!NILP (Vdisplay_line_numbers) && it->line_number_produced_p)
 31659         {
 31660           /* If the line is hscrolled, and the stretch starts before
 31661              the first visible pixel, simulate negative row->x.  */
 31662           if (x < it->first_visible_x)
 31663             {
 31664               next_x -= it->first_visible_x - x;
 31665               it->stretch_adjust = it->first_visible_x - x;
 31666             }
 31667           else
 31668             next_x -= it->stretch_adjust;
 31669         }
 31670       width = next_x - x0;
 31671       zero_width_ok_p = true;
 31672     }
 31673   else
 31674     /* Nothing specified -> width defaults to canonical char width.  */
 31675     width = FRAME_COLUMN_WIDTH (it->f);
 31676 
 31677   if (width <= 0 && (width < 0 || !zero_width_ok_p))
 31678     width = 1;
 31679 
 31680 #ifdef HAVE_WINDOW_SYSTEM
 31681   /* Compute height.  */
 31682   if (FRAME_WINDOW_P (it->f))
 31683     {
 31684       int default_height = normal_char_height (font, ' ');
 31685 
 31686       if ((prop = plist_get (plist, QCheight), !NILP (prop))
 31687           && calc_pixel_width_or_height (&tem, it, prop, font, false, NULL))
 31688         {
 31689           height = (int)tem;
 31690           zero_height_ok_p = true;
 31691         }
 31692       else if (prop = plist_get (plist, QCrelative_height),
 31693                NUMVAL (prop) > 0)
 31694         height = default_height * NUMVAL (prop);
 31695       else
 31696         height = default_height;
 31697 
 31698       if (height <= 0 && (height < 0 || !zero_height_ok_p))
 31699         height = 1;
 31700 
 31701       /* Compute percentage of height used for ascent.  If
 31702          `:ascent ASCENT' is present and valid, use that.  Otherwise,
 31703          derive the ascent from the font in use.  */
 31704       if (prop = plist_get (plist, QCascent),
 31705           NUMVAL (prop) > 0 && NUMVAL (prop) <= 100)
 31706         ascent = height * NUMVAL (prop) / 100.0;
 31707       else if (!NILP (prop)
 31708                && calc_pixel_width_or_height (&tem, it, prop, font, false, 0))
 31709         ascent = min (max (0, (int)tem), height);
 31710       else
 31711         ascent = (height * FONT_BASE (font)) / FONT_HEIGHT (font);
 31712     }
 31713   else
 31714 #endif  /* HAVE_WINDOW_SYSTEM */
 31715     height = 1;
 31716 
 31717   if (width > 0
 31718       && it->area == TEXT_AREA && it->line_wrap != TRUNCATE
 31719       && it->current_x + width > it->last_visible_x)
 31720     {
 31721       width = it->last_visible_x - it->current_x;
 31722 #ifdef HAVE_WINDOW_SYSTEM
 31723       /* Subtract one more pixel from the stretch width, but only on
 31724          GUI frames, since on a TTY each glyph is one "pixel" wide.  */
 31725       width -= FRAME_WINDOW_P (it->f);
 31726 #endif
 31727     }
 31728 
 31729   if (width > 0 && height > 0 && it->glyph_row)
 31730     {
 31731       Lisp_Object o_object = it->object;
 31732       Lisp_Object object =
 31733         it->sp > 0 ? it->stack[it->sp - 1].string : it->string;
 31734       int n = width;
 31735 
 31736       if (!STRINGP (object))
 31737         object = it->w->contents;
 31738 #ifdef HAVE_WINDOW_SYSTEM
 31739       if (FRAME_WINDOW_P (it->f))
 31740         append_stretch_glyph (it, object, width, height, ascent);
 31741       else
 31742 #endif
 31743         {
 31744           it->object = object;
 31745           it->char_to_display = ' ';
 31746           it->pixel_width = it->len = 1;
 31747           while (n--)
 31748             tty_append_glyph (it);
 31749           it->object = o_object;
 31750         }
 31751     }
 31752 
 31753   it->pixel_width = width;
 31754 #ifdef HAVE_WINDOW_SYSTEM
 31755   if (FRAME_WINDOW_P (it->f))
 31756     {
 31757       it->ascent = it->phys_ascent = ascent;
 31758       it->descent = it->phys_descent = height - it->ascent;
 31759       it->nglyphs = width > 0 && height > 0;
 31760       take_vertical_position_into_account (it);
 31761     }
 31762   else
 31763 #endif
 31764     it->nglyphs = width;
 31765 }
 31766 
 31767 /* Get information about special display element WHAT in an
 31768    environment described by IT.  WHAT is one of IT_TRUNCATION or
 31769    IT_CONTINUATION.  Maybe produce glyphs for WHAT if IT has a
 31770    non-null glyph_row member.  This function ensures that fields like
 31771    face_id, c, len of IT are left untouched.  */
 31772 
 31773 static void
 31774 produce_special_glyphs (struct it *it, enum display_element_type what)
 31775 {
 31776   struct it temp_it;
 31777   Lisp_Object gc;
 31778   GLYPH glyph;
 31779 
 31780   temp_it = *it;
 31781   temp_it.object = Qnil;
 31782   memset (&temp_it.current, 0, sizeof temp_it.current);
 31783 
 31784   if (what == IT_CONTINUATION)
 31785     {
 31786       /* Continuation glyph.  For R2L lines, we mirror it by hand.  */
 31787       if (it->bidi_it.paragraph_dir == R2L)
 31788         SET_GLYPH_FROM_CHAR (glyph, '/');
 31789       else
 31790         SET_GLYPH_FROM_CHAR (glyph, '\\');
 31791       if (it->dp
 31792           && (gc = DISP_CONTINUE_GLYPH (it->dp), GLYPH_CODE_P (gc)))
 31793         {
 31794           /* FIXME: Should we mirror GC for R2L lines?  */
 31795           SET_GLYPH_FROM_GLYPH_CODE (glyph, gc);
 31796           spec_glyph_lookup_face (XWINDOW (it->window), &glyph);
 31797         }
 31798     }
 31799   else if (what == IT_TRUNCATION)
 31800     {
 31801       /* Truncation glyph.  */
 31802       SET_GLYPH_FROM_CHAR (glyph, '$');
 31803       if (it->dp
 31804           && (gc = DISP_TRUNC_GLYPH (it->dp), GLYPH_CODE_P (gc)))
 31805         {
 31806           /* FIXME: Should we mirror GC for R2L lines?  */
 31807           SET_GLYPH_FROM_GLYPH_CODE (glyph, gc);
 31808           spec_glyph_lookup_face (XWINDOW (it->window), &glyph);
 31809         }
 31810     }
 31811   else
 31812     emacs_abort ();
 31813 
 31814 #ifdef HAVE_WINDOW_SYSTEM
 31815   /* On a GUI frame, when the right fringe (left fringe for R2L rows)
 31816      is turned off, we precede the truncation/continuation glyphs by a
 31817      stretch glyph whose width is computed such that these special
 31818      glyphs are aligned at the window margin, even when very different
 31819      fonts are used in different glyph rows.  */
 31820   if (FRAME_WINDOW_P (temp_it.f)
 31821       /* init_iterator calls this with it->glyph_row == NULL, and it
 31822          wants only the pixel width of the truncation/continuation
 31823          glyphs.  */
 31824       && temp_it.glyph_row
 31825       /* insert_left_trunc_glyphs calls us at the beginning of the
 31826          row, and it has its own calculation of the stretch glyph
 31827          width.  */
 31828       && temp_it.glyph_row->used[TEXT_AREA] > 0
 31829       && (temp_it.glyph_row->reversed_p
 31830           ? WINDOW_LEFT_FRINGE_WIDTH (temp_it.w)
 31831           : WINDOW_RIGHT_FRINGE_WIDTH (temp_it.w)) == 0)
 31832     {
 31833       int stretch_width = temp_it.last_visible_x - temp_it.current_x;
 31834 
 31835       if (stretch_width > 0)
 31836         {
 31837           struct face *face = FACE_FROM_ID (temp_it.f, temp_it.face_id);
 31838           struct font *font =
 31839             face->font ? face->font : FRAME_FONT (temp_it.f);
 31840           int stretch_ascent =
 31841             (((temp_it.ascent + temp_it.descent)
 31842               * FONT_BASE (font)) / FONT_HEIGHT (font));
 31843 
 31844           append_stretch_glyph (&temp_it, Qnil, stretch_width,
 31845                                 temp_it.ascent + temp_it.descent,
 31846                                 stretch_ascent);
 31847         }
 31848     }
 31849 #endif
 31850 
 31851   temp_it.dp = NULL;
 31852   temp_it.what = IT_CHARACTER;
 31853   temp_it.c = temp_it.char_to_display = GLYPH_CHAR (glyph);
 31854   temp_it.face_id = GLYPH_FACE (glyph);
 31855   temp_it.len = CHAR_BYTES (temp_it.c);
 31856 
 31857   PRODUCE_GLYPHS (&temp_it);
 31858   it->pixel_width = temp_it.pixel_width;
 31859   it->nglyphs = temp_it.nglyphs;
 31860 }
 31861 
 31862 /* Produce padding glyphs for mode/header/tab-line whose text needs to
 31863    be truncated.  This is used when the last visible character leaves
 31864    one or more columns till the window edge, but the next character is
 31865    wider than that number of columns, and therefore cannot fit on the
 31866    line.  We then replace these columns with the appropriate padding
 31867    character: '-' for the mode line and SPC for the other two.  That's
 31868    because these lines should not show the usual truncation glyphs
 31869    there.  This function is only used on TTY frames.  */
 31870 static void
 31871 pad_mode_line (struct it *it, bool mode_line_p)
 31872 {
 31873   struct it temp_it;
 31874   GLYPH glyph;
 31875 
 31876   eassert (!FRAME_WINDOW_P (it->f));
 31877   temp_it = *it;
 31878   temp_it.object = Qnil;
 31879   memset (&temp_it.current, 0, sizeof temp_it.current);
 31880 
 31881   SET_GLYPH (glyph, mode_line_p ? '-' : ' ', it->base_face_id);
 31882 
 31883   temp_it.dp = NULL;
 31884   temp_it.what = IT_CHARACTER;
 31885   temp_it.c = temp_it.char_to_display = GLYPH_CHAR (glyph);
 31886   temp_it.face_id = GLYPH_FACE (glyph);
 31887   temp_it.len = CHAR_BYTES (temp_it.c);
 31888 
 31889   PRODUCE_GLYPHS (&temp_it);
 31890   it->pixel_width = temp_it.pixel_width;
 31891   it->nglyphs = temp_it.nglyphs;
 31892 }
 31893 
 31894 #ifdef HAVE_WINDOW_SYSTEM
 31895 
 31896 /* Calculate line-height and line-spacing properties.
 31897    An integer value specifies explicit pixel value.
 31898    A float value specifies relative value to current face height.
 31899    A cons (float . face-name) specifies relative value to
 31900    height of specified face font.
 31901 
 31902    Returns height in pixels, or nil.  */
 31903 
 31904 static Lisp_Object
 31905 calc_line_height_property (struct it *it, Lisp_Object val, struct font *font,
 31906                            int boff, bool override)
 31907 {
 31908   Lisp_Object face_name = Qnil;
 31909   int ascent, descent, height;
 31910 
 31911   if (NILP (val) || INTEGERP (val) || (override && EQ (val, Qt)))
 31912     return val;
 31913 
 31914   if (CONSP (val))
 31915     {
 31916       face_name = XCAR (val);
 31917       val = XCDR (val);
 31918       if (!NUMBERP (val))
 31919         val = make_fixnum (1);
 31920       if (NILP (face_name))
 31921         {
 31922           height = it->ascent + it->descent;
 31923           goto scale;
 31924         }
 31925     }
 31926 
 31927   if (NILP (face_name))
 31928     {
 31929       font = FRAME_FONT (it->f);
 31930       boff = FRAME_BASELINE_OFFSET (it->f);
 31931     }
 31932   else if (EQ (face_name, Qt))
 31933     {
 31934       override = false;
 31935     }
 31936   else
 31937     {
 31938       int face_id;
 31939       struct face *face;
 31940 
 31941       face_id = lookup_named_face (it->w, it->f, face_name, false);
 31942       face = FACE_FROM_ID_OR_NULL (it->f, face_id);
 31943       if (face == NULL || ((font = face->font) == NULL))
 31944         return make_fixnum (-1);
 31945       boff = font->baseline_offset;
 31946       if (font->vertical_centering)
 31947         boff = VCENTER_BASELINE_OFFSET (font, it->f) - boff;
 31948     }
 31949 
 31950   normal_char_ascent_descent (font, -1, &ascent, &descent);
 31951 
 31952   if (override)
 31953     {
 31954       it->override_ascent = ascent;
 31955       it->override_descent = descent;
 31956       it->override_boff = boff;
 31957     }
 31958 
 31959   height = ascent + descent;
 31960 
 31961  scale:
 31962   /* FIXME: Check for overflow in multiplication or conversion.  */
 31963   if (FLOATP (val))
 31964     height = (int)(XFLOAT_DATA (val) * height);
 31965   else if (INTEGERP (val))
 31966     {
 31967       intmax_t v;
 31968       if (integer_to_intmax (val, &v))
 31969         height *= v;
 31970     }
 31971 
 31972   return make_fixnum (height);
 31973 }
 31974 
 31975 
 31976 /* Append a glyph for a glyphless character to IT->glyph_row.  FACE_ID
 31977    is a face ID to be used for the glyph.  FOR_NO_FONT is true if
 31978    and only if this is for a character for which no font was found.
 31979 
 31980    If the display method (it->glyphless_method) is
 31981    GLYPHLESS_DISPLAY_ACRONYM or GLYPHLESS_DISPLAY_HEX_CODE, LEN is a
 31982    length of the acronym or the hexadecimal string, UPPER_XOFF and
 31983    UPPER_YOFF are pixel offsets for the upper part of the string,
 31984    LOWER_XOFF and LOWER_YOFF are for the lower part.
 31985 
 31986    For the other display methods, LEN through LOWER_YOFF are zero.  */
 31987 
 31988 static void
 31989 append_glyphless_glyph (struct it *it, int face_id, bool for_no_font, int len,
 31990                         short upper_xoff, short upper_yoff,
 31991                         short lower_xoff, short lower_yoff)
 31992 {
 31993   struct glyph *glyph;
 31994   enum glyph_row_area area = it->area;
 31995 
 31996   glyph = it->glyph_row->glyphs[area] + it->glyph_row->used[area];
 31997   if (glyph < it->glyph_row->glyphs[area + 1])
 31998     {
 31999       /* If the glyph row is reversed, we need to prepend the glyph
 32000          rather than append it.  */
 32001       if (it->glyph_row->reversed_p && area == TEXT_AREA)
 32002         {
 32003           struct glyph *g;
 32004 
 32005           /* Make room for the additional glyph.  */
 32006           for (g = glyph - 1; g >= it->glyph_row->glyphs[area]; g--)
 32007             g[1] = *g;
 32008           glyph = it->glyph_row->glyphs[area];
 32009         }
 32010       glyph->charpos = CHARPOS (it->position);
 32011       glyph->object = it->object;
 32012       eassert (it->pixel_width <= SHRT_MAX);
 32013       glyph->pixel_width = it->pixel_width;
 32014       glyph->ascent = it->ascent;
 32015       glyph->descent = it->descent;
 32016       glyph->voffset = it->voffset;
 32017       glyph->type = GLYPHLESS_GLYPH;
 32018       glyph->u.glyphless.method = it->glyphless_method;
 32019       glyph->u.glyphless.for_no_font = for_no_font;
 32020       glyph->u.glyphless.len = len;
 32021       glyph->u.glyphless.ch = it->c;
 32022       glyph->slice.glyphless.upper_xoff = upper_xoff;
 32023       glyph->slice.glyphless.upper_yoff = upper_yoff;
 32024       glyph->slice.glyphless.lower_xoff = lower_xoff;
 32025       glyph->slice.glyphless.lower_yoff = lower_yoff;
 32026       glyph->avoid_cursor_p = it->avoid_cursor_p;
 32027       glyph->multibyte_p = it->multibyte_p;
 32028       if (it->glyph_row->reversed_p && area == TEXT_AREA)
 32029         {
 32030           /* In R2L rows, the left and the right box edges need to be
 32031              drawn in reverse direction.  */
 32032           glyph->right_box_line_p = it->start_of_box_run_p;
 32033           glyph->left_box_line_p = it->end_of_box_run_p;
 32034         }
 32035       else
 32036         {
 32037           glyph->left_box_line_p = it->start_of_box_run_p;
 32038           glyph->right_box_line_p = it->end_of_box_run_p;
 32039         }
 32040       glyph->overlaps_vertically_p = (it->phys_ascent > it->ascent
 32041                                       || it->phys_descent > it->descent);
 32042       glyph->padding_p = false;
 32043       glyph->glyph_not_available_p = false;
 32044       glyph->face_id = face_id;
 32045       glyph->font_type = FONT_TYPE_UNKNOWN;
 32046       if (it->bidi_p)
 32047         {
 32048           glyph->resolved_level = it->bidi_it.resolved_level;
 32049           eassert ((it->bidi_it.type & 7) == it->bidi_it.type);
 32050           glyph->bidi_type = it->bidi_it.type;
 32051         }
 32052       ++it->glyph_row->used[area];
 32053     }
 32054   else
 32055     IT_EXPAND_MATRIX_WIDTH (it, area);
 32056 }
 32057 
 32058 
 32059 /* Produce a glyph for a glyphless character for iterator IT.
 32060    IT->glyphless_method specifies which method to use for displaying
 32061    the character.  See the description of enum
 32062    glyphless_display_method in dispextern.h for the detail.
 32063 
 32064    FOR_NO_FONT is true if and only if this is for a character for
 32065    which no font was found.  ACRONYM, if non-nil, is an acronym string
 32066    for the character.  */
 32067 
 32068 static void
 32069 produce_glyphless_glyph (struct it *it, bool for_no_font, Lisp_Object acronym)
 32070 {
 32071   int face_id;
 32072   struct face *face;
 32073   struct font *font;
 32074   int base_width, base_height, width, height;
 32075   short upper_xoff, upper_yoff, lower_xoff, lower_yoff;
 32076   int len;
 32077 
 32078   /* Get the metrics of the base font.  We always refer to the current
 32079      ASCII face.  */
 32080   face = FACE_FROM_ID (it->f, it->face_id)->ascii_face;
 32081   font = face->font ? face->font : FRAME_FONT (it->f);
 32082   normal_char_ascent_descent (font, -1, &it->ascent, &it->descent);
 32083   it->ascent += font->baseline_offset;
 32084   it->descent -= font->baseline_offset;
 32085   base_height = it->ascent + it->descent;
 32086   base_width = font->average_width;
 32087 
 32088   face_id = merge_glyphless_glyph_face (it);
 32089 
 32090   if (it->glyphless_method == GLYPHLESS_DISPLAY_THIN_SPACE)
 32091     {
 32092       it->pixel_width = THIN_SPACE_WIDTH;
 32093       len = 0;
 32094       upper_xoff = upper_yoff = lower_xoff = lower_yoff = 0;
 32095     }
 32096   else if (it->glyphless_method == GLYPHLESS_DISPLAY_EMPTY_BOX)
 32097     {
 32098       width = CHARACTER_WIDTH (it->c);
 32099       if (width == 0)
 32100         width = 1;
 32101       else if (width > 4)
 32102         width = 4;
 32103       it->pixel_width = base_width * width;
 32104       len = 0;
 32105       upper_xoff = upper_yoff = lower_xoff = lower_yoff = 0;
 32106     }
 32107   else
 32108     {
 32109       char buf[7];
 32110       const char *str;
 32111       unsigned int code[6];
 32112       int upper_len;
 32113       int ascent, descent;
 32114       struct font_metrics metrics_upper, metrics_lower;
 32115 
 32116       face = FACE_FROM_ID (it->f, face_id);
 32117       font = face->font ? face->font : FRAME_FONT (it->f);
 32118       prepare_face_for_display (it->f, face);
 32119 
 32120       if (it->glyphless_method == GLYPHLESS_DISPLAY_ACRONYM)
 32121         {
 32122           if (! STRINGP (acronym) && CHAR_TABLE_P (Vglyphless_char_display))
 32123             acronym = CHAR_TABLE_REF (Vglyphless_char_display, it->c);
 32124           if (CONSP (acronym))
 32125             acronym = XCAR (acronym);
 32126           str = STRINGP (acronym) ? SSDATA (acronym) : "";
 32127         }
 32128       else
 32129         {
 32130           eassert (it->glyphless_method == GLYPHLESS_DISPLAY_HEX_CODE);
 32131           sprintf (buf, "%0*X", it->c < 0x10000 ? 4 : 6, it->c + 0u);
 32132           str = buf;
 32133         }
 32134       for (len = 0; str[len] && ASCII_CHAR_P (str[len]) && len < 6; len++)
 32135         code[len] = font->driver->encode_char (font, str[len]);
 32136       upper_len = (len + 1) / 2;
 32137       font->driver->text_extents (font, code, upper_len,
 32138                                   &metrics_upper);
 32139       font->driver->text_extents (font, code + upper_len, len - upper_len,
 32140                                   &metrics_lower);
 32141 
 32142 
 32143 
 32144       /* +4 is for vertical bars of a box plus 1-pixel spaces at both side.  */
 32145       width = max (metrics_upper.width, metrics_lower.width) + 4;
 32146       upper_xoff = lower_xoff = 2; /* the typical case */
 32147       if (base_width >= width)
 32148         {
 32149           /* Align the upper to the left, the lower to the right.  */
 32150           it->pixel_width = base_width;
 32151           lower_xoff = base_width - 2 - metrics_lower.width;
 32152         }
 32153       else
 32154         {
 32155           /* Center the shorter one.  */
 32156           it->pixel_width = width;
 32157           if (metrics_upper.width >= metrics_lower.width)
 32158             lower_xoff = (width - metrics_lower.width) / 2;
 32159           else
 32160             upper_xoff = (width - metrics_upper.width) / 2;
 32161         }
 32162 
 32163       /* +5 is for horizontal bars of a box plus 1-pixel spaces at
 32164          top, bottom, and between upper and lower strings.  */
 32165       height = (metrics_upper.ascent + metrics_upper.descent
 32166                 + metrics_lower.ascent + metrics_lower.descent) + 5;
 32167       /* Center vertically.
 32168          H:base_height, D:base_descent
 32169          h:height, ld:lower_descent, la:lower_ascent, ud:upper_descent
 32170 
 32171          ascent = - (D - H/2 - h/2 + 1); "+ 1" for rounding up
 32172          descent = D - H/2 + h/2;
 32173          lower_yoff = descent - 2 - ld;
 32174          upper_yoff = lower_yoff - la - 1 - ud;  */
 32175       ascent = - (it->descent - (base_height + height + 1) / 2);
 32176       descent = it->descent - (base_height - height) / 2;
 32177       lower_yoff = descent - 2 - metrics_lower.descent;
 32178       upper_yoff = (lower_yoff - metrics_lower.ascent - 1
 32179                     - metrics_upper.descent);
 32180       /* Don't make the height shorter than the base height.  */
 32181       if (height > base_height)
 32182         {
 32183           it->ascent = ascent;
 32184           it->descent = descent;
 32185         }
 32186     }
 32187 
 32188   it->phys_ascent = it->ascent;
 32189   it->phys_descent = it->descent;
 32190   if (it->glyph_row)
 32191     append_glyphless_glyph (it, face_id, for_no_font, len,
 32192                             upper_xoff, upper_yoff,
 32193                             lower_xoff, lower_yoff);
 32194   it->nglyphs = 1;
 32195   take_vertical_position_into_account (it);
 32196 }
 32197 
 32198 
 32199 /* If face has a box, add the box thickness to the character
 32200    height.  If character has a box line to the left and/or
 32201    right, add the box line width to the character's width.  */
 32202 #define IT_APPLY_FACE_BOX(it, face)                             \
 32203   do {                                                          \
 32204     if (face->box != FACE_NO_BOX)                               \
 32205       {                                                         \
 32206         int thick = face->box_horizontal_line_width;            \
 32207         if (thick > 0)                                          \
 32208           {                                                     \
 32209             it->ascent += thick;                                \
 32210             it->descent += thick;                               \
 32211           }                                                     \
 32212                                                                 \
 32213         thick = face->box_vertical_line_width;                  \
 32214         if (thick > 0)                                          \
 32215           {                                                     \
 32216             if (it->start_of_box_run_p)                         \
 32217               it->pixel_width += thick;                         \
 32218             if (it->end_of_box_run_p)                           \
 32219               it->pixel_width += thick;                         \
 32220           }                                                     \
 32221       }                                                         \
 32222     } while (false)
 32223 
 32224 /* RIF:
 32225    Produce glyphs/get display metrics for the display element IT is
 32226    loaded with.  See the description of struct it in dispextern.h
 32227    for an overview of struct it.  */
 32228 
 32229 void
 32230 gui_produce_glyphs (struct it *it)
 32231 {
 32232   int extra_line_spacing = it->extra_line_spacing;
 32233 
 32234   it->glyph_not_available_p = false;
 32235 
 32236   if (it->what == IT_CHARACTER)
 32237     {
 32238       unsigned char2b;
 32239       struct face *face = FACE_FROM_ID (it->f, it->face_id);
 32240       struct font *font = face->font;
 32241       struct font_metrics *pcm = NULL;
 32242       int boff;                 /* Baseline offset.  */
 32243 
 32244       if (font == NULL)
 32245         {
 32246           /* When no suitable font is found, display this character by
 32247              the method specified in the first extra slot of
 32248              Vglyphless_char_display.  */
 32249           Lisp_Object acronym = lookup_glyphless_char_display (-1, it);
 32250 
 32251           eassert (it->what == IT_GLYPHLESS);
 32252           produce_glyphless_glyph (it, true,
 32253                                    STRINGP (acronym) ? acronym : Qnil);
 32254           goto done;
 32255         }
 32256 
 32257       boff = font->baseline_offset;
 32258       if (font->vertical_centering)
 32259         boff = VCENTER_BASELINE_OFFSET (font, it->f) - boff;
 32260 
 32261       if (it->char_to_display != '\n' && it->char_to_display != '\t')
 32262         {
 32263           it->nglyphs = 1;
 32264 
 32265           if (it->override_ascent >= 0)
 32266             {
 32267               it->ascent = it->override_ascent;
 32268               it->descent = it->override_descent;
 32269               boff = it->override_boff;
 32270             }
 32271           else
 32272             {
 32273               it->ascent = FONT_BASE (font) + boff;
 32274               it->descent = FONT_DESCENT (font) - boff;
 32275             }
 32276 
 32277           if (get_char_glyph_code (it->char_to_display, font, &char2b))
 32278             {
 32279               pcm = get_per_char_metric (font, &char2b);
 32280               if (pcm->width == 0
 32281                   && pcm->rbearing == 0 && pcm->lbearing == 0)
 32282                 pcm = NULL;
 32283             }
 32284 
 32285           if (pcm)
 32286             {
 32287               it->phys_ascent = pcm->ascent + boff;
 32288               it->phys_descent = pcm->descent - boff;
 32289               it->pixel_width = pcm->width;
 32290               /* Don't use font-global values for ascent and descent
 32291                  if they result in an exceedingly large line height.  */
 32292               if (it->override_ascent < 0)
 32293                 {
 32294                   if (FONT_TOO_HIGH (font))
 32295                     {
 32296                       it->ascent = it->phys_ascent;
 32297                       it->descent = it->phys_descent;
 32298                       /* These limitations are enforced by an
 32299                          assertion near the end of this function.  */
 32300                       if (it->ascent < 0)
 32301                         it->ascent = 0;
 32302                       if (it->descent < 0)
 32303                         it->descent = 0;
 32304                     }
 32305                 }
 32306             }
 32307           else
 32308             {
 32309               it->glyph_not_available_p = true;
 32310               it->phys_ascent = it->ascent;
 32311               it->phys_descent = it->descent;
 32312               it->pixel_width = font->space_width;
 32313             }
 32314 
 32315           if (it->constrain_row_ascent_descent_p)
 32316             {
 32317               if (it->descent > it->max_descent)
 32318                 {
 32319                   it->ascent += it->descent - it->max_descent;
 32320                   it->descent = it->max_descent;
 32321                 }
 32322               if (it->ascent > it->max_ascent)
 32323                 {
 32324                   it->descent = min (it->max_descent, it->descent + it->ascent - it->max_ascent);
 32325                   it->ascent = it->max_ascent;
 32326                 }
 32327               it->phys_ascent = min (it->phys_ascent, it->ascent);
 32328               it->phys_descent = min (it->phys_descent, it->descent);
 32329               extra_line_spacing = 0;
 32330             }
 32331 
 32332           /* If this is a space inside a region of text with
 32333              `space-width' property, change its width.  */
 32334           bool stretched_p
 32335             = it->char_to_display == ' ' && !NILP (it->space_width);
 32336           if (stretched_p)
 32337             it->pixel_width *= XFLOATINT (it->space_width);
 32338 
 32339           IT_APPLY_FACE_BOX(it, face);
 32340 
 32341           /* If face has an overline, add the height of the overline
 32342              (1 pixel) and a 1 pixel margin to the character height.  */
 32343           if (face->overline_p)
 32344             it->ascent += clip_to_bounds (0, overline_margin, 1000000);
 32345 
 32346           if (it->constrain_row_ascent_descent_p)
 32347             {
 32348               if (it->ascent > it->max_ascent)
 32349                 it->ascent = it->max_ascent;
 32350               if (it->descent > it->max_descent)
 32351                 it->descent = it->max_descent;
 32352             }
 32353 
 32354           take_vertical_position_into_account (it);
 32355 
 32356           /* If we have to actually produce glyphs, do it.  */
 32357           if (it->glyph_row)
 32358             {
 32359               if (stretched_p)
 32360                 {
 32361                   /* Translate a space with a `space-width' property
 32362                      into a stretch glyph.  */
 32363                   int ascent = (((it->ascent + it->descent) * FONT_BASE (font))
 32364                                 / FONT_HEIGHT (font));
 32365                   append_stretch_glyph (it, it->object, it->pixel_width,
 32366                                         it->ascent + it->descent, ascent);
 32367                 }
 32368               else
 32369                 append_glyph (it);
 32370 
 32371               /* If characters with lbearing or rbearing are displayed
 32372                  in this line, record that fact in a flag of the
 32373                  glyph row.  This is used to optimize X output code.  */
 32374               if (pcm && (pcm->lbearing < 0 || pcm->rbearing > pcm->width))
 32375                 it->glyph_row->contains_overlapping_glyphs_p = true;
 32376             }
 32377           if (! stretched_p && it->pixel_width == 0)
 32378             /* We assure that all visible glyphs have at least 1-pixel
 32379                width.  */
 32380             it->pixel_width = 1;
 32381         }
 32382       else if (it->char_to_display == '\n')
 32383         {
 32384           /* A newline has no width, but we need the height of the
 32385              line.  But if previous part of the line sets a height,
 32386              don't increase that height.  */
 32387 
 32388           Lisp_Object height;
 32389           Lisp_Object total_height = Qnil;
 32390 
 32391           it->override_ascent = -1;
 32392           it->pixel_width = 0;
 32393           it->nglyphs = 0;
 32394 
 32395           height = get_it_property (it, Qline_height);
 32396           /* Split (line-height total-height) list.  */
 32397           if (CONSP (height)
 32398               && CONSP (XCDR (height))
 32399               && NILP (XCDR (XCDR (height))))
 32400             {
 32401               total_height = XCAR (XCDR (height));
 32402               height = XCAR (height);
 32403             }
 32404           height = calc_line_height_property (it, height, font, boff, true);
 32405 
 32406           if (it->override_ascent >= 0)
 32407             {
 32408               it->ascent = it->override_ascent;
 32409               it->descent = it->override_descent;
 32410               boff = it->override_boff;
 32411             }
 32412           else
 32413             {
 32414               if (FONT_TOO_HIGH (font))
 32415                 {
 32416                   it->ascent = font->pixel_size + boff - 1;
 32417                   it->descent = -boff + 1;
 32418                   if (it->descent < 0)
 32419                     it->descent = 0;
 32420                 }
 32421               else
 32422                 {
 32423                   it->ascent = FONT_BASE (font) + boff;
 32424                   it->descent = FONT_DESCENT (font) - boff;
 32425                 }
 32426             }
 32427 
 32428           if (EQ (height, Qt))
 32429             {
 32430               if (it->descent > it->max_descent)
 32431                 {
 32432                   it->ascent += it->descent - it->max_descent;
 32433                   it->descent = it->max_descent;
 32434                 }
 32435               if (it->ascent > it->max_ascent)
 32436                 {
 32437                   it->descent = min (it->max_descent, it->descent + it->ascent - it->max_ascent);
 32438                   it->ascent = it->max_ascent;
 32439                 }
 32440               it->phys_ascent = min (it->phys_ascent, it->ascent);
 32441               it->phys_descent = min (it->phys_descent, it->descent);
 32442               it->constrain_row_ascent_descent_p = true;
 32443               extra_line_spacing = 0;
 32444             }
 32445           else
 32446             {
 32447               Lisp_Object spacing;
 32448 
 32449               it->phys_ascent = it->ascent;
 32450               it->phys_descent = it->descent;
 32451 
 32452               if ((it->max_ascent > 0 || it->max_descent > 0)
 32453                   && face->box != FACE_NO_BOX
 32454                   && face->box_horizontal_line_width > 0)
 32455                 {
 32456                   it->ascent += face->box_horizontal_line_width;
 32457                   it->descent += face->box_horizontal_line_width;
 32458                 }
 32459               if (!NILP (height)
 32460                   && XFIXNUM (height) > it->ascent + it->descent)
 32461                 it->ascent = XFIXNUM (height) - it->descent;
 32462 
 32463               if (!NILP (total_height))
 32464                 spacing = calc_line_height_property (it, total_height, font,
 32465                                                      boff, false);
 32466               else
 32467                 {
 32468                   spacing = get_it_property (it, Qline_spacing);
 32469                   spacing = calc_line_height_property (it, spacing, font,
 32470                                                        boff, false);
 32471                 }
 32472               if (FIXNUMP (spacing))
 32473                 {
 32474                   extra_line_spacing = XFIXNUM (spacing);
 32475                   if (!NILP (total_height))
 32476                     extra_line_spacing -= (it->phys_ascent + it->phys_descent);
 32477                 }
 32478             }
 32479         }
 32480       else                    /* i.e. (it->char_to_display == '\t') */
 32481         {
 32482           if (font->space_width > 0)
 32483             {
 32484               int tab_width = it->tab_width * font->space_width;
 32485               int x = it->current_x + it->continuation_lines_width;
 32486               int x0 = x;
 32487               /* Adjust for line numbers, if needed.   */
 32488               if (!NILP (Vdisplay_line_numbers) && it->line_number_produced_p)
 32489                 {
 32490                   x -= it->lnum_pixel_width;
 32491                   /* Restore the original TAB width, if required.  */
 32492                   if (x + it->stretch_adjust >= it->first_visible_x)
 32493                     x += it->stretch_adjust;
 32494                 }
 32495 
 32496               int next_tab_x = ((1 + x + tab_width - 1) / tab_width) * tab_width;
 32497 
 32498               /* If the distance from the current position to the next tab
 32499                  stop is less than a space character width, use the
 32500                  tab stop after that.  */
 32501               if (next_tab_x - x < font->space_width)
 32502                 next_tab_x += tab_width;
 32503               if (!NILP (Vdisplay_line_numbers) && it->line_number_produced_p)
 32504                 {
 32505                   next_tab_x += it->lnum_pixel_width;
 32506                   /* If the line is hscrolled, and the TAB starts before
 32507                      the first visible pixel, simulate negative row->x.  */
 32508                   if (x < it->first_visible_x)
 32509                     {
 32510                       next_tab_x -= it->first_visible_x - x;
 32511                       it->stretch_adjust = it->first_visible_x - x;
 32512                     }
 32513                   else
 32514                     next_tab_x -= it->stretch_adjust;
 32515                 }
 32516 
 32517               it->pixel_width = next_tab_x - x0;
 32518               it->nglyphs = 1;
 32519               if (FONT_TOO_HIGH (font))
 32520                 {
 32521                   if (get_char_glyph_code (' ', font, &char2b))
 32522                     {
 32523                       pcm = get_per_char_metric (font, &char2b);
 32524                       if (pcm->width == 0
 32525                           && pcm->rbearing == 0 && pcm->lbearing == 0)
 32526                         pcm = NULL;
 32527                     }
 32528 
 32529                   if (pcm)
 32530                     {
 32531                       it->ascent = pcm->ascent + boff;
 32532                       it->descent = pcm->descent - boff;
 32533                     }
 32534                   else
 32535                     {
 32536                       it->ascent = font->pixel_size + boff - 1;
 32537                       it->descent = -boff + 1;
 32538                     }
 32539                   if (it->ascent < 0)
 32540                     it->ascent = 0;
 32541                   if (it->descent < 0)
 32542                     it->descent = 0;
 32543                 }
 32544               else
 32545                 {
 32546                   it->ascent = FONT_BASE (font) + boff;
 32547                   it->descent = FONT_DESCENT (font) - boff;
 32548                 }
 32549               it->phys_ascent = it->ascent;
 32550               it->phys_descent = it->descent;
 32551 
 32552               if (it->glyph_row)
 32553                 {
 32554                   append_stretch_glyph (it, it->object, it->pixel_width,
 32555                                         it->ascent + it->descent, it->ascent);
 32556                 }
 32557             }
 32558           else
 32559             {
 32560               it->pixel_width = 0;
 32561               it->nglyphs = 1;
 32562             }
 32563         }
 32564 
 32565       if (FONT_TOO_HIGH (font))
 32566         {
 32567           int font_ascent, font_descent;
 32568 
 32569           /* For very large fonts, where we ignore the declared font
 32570              dimensions, and go by per-character metrics instead,
 32571              don't let the row ascent and descent values (and the row
 32572              height computed from them) be smaller than the "normal"
 32573              character metrics.  This avoids unpleasant effects
 32574              whereby lines on display would change their height
 32575              depending on which characters are shown.  */
 32576           normal_char_ascent_descent (font, -1, &font_ascent, &font_descent);
 32577           it->max_ascent = max (it->max_ascent, font_ascent);
 32578           it->max_descent = max (it->max_descent, font_descent);
 32579         }
 32580 
 32581       if (it->ascent < 0)
 32582         it->ascent = 0;
 32583       if (it->descent < 0)
 32584         it->descent = 0;
 32585     }
 32586   else if (it->what == IT_COMPOSITION && it->cmp_it.ch < 0)
 32587     {
 32588       /* A static composition.
 32589 
 32590          Note: A composition is represented as one glyph in the
 32591          glyph matrix.  There are no padding glyphs.
 32592 
 32593          Important note: pixel_width, ascent, and descent are the
 32594          values of what is drawn by draw_glyphs (i.e. the values of
 32595          the overall glyphs composed).  */
 32596       struct face *face = FACE_FROM_ID (it->f, it->face_id);
 32597       int boff;                 /* baseline offset */
 32598       struct composition *cmp = composition_table[it->cmp_it.id];
 32599       int glyph_len = cmp->glyph_len;
 32600       struct font *font = face->font;
 32601 
 32602       it->nglyphs = 1;
 32603 
 32604       /* If we have not yet calculated pixel size data of glyphs of
 32605          the composition for the current face font, calculate them
 32606          now.  Theoretically, we have to check all fonts for the
 32607          glyphs, but that requires much time and memory space.  So,
 32608          here we check only the font of the first glyph.  This may
 32609          lead to incorrect display, but it's very rare, and C-l
 32610          (recenter-top-bottom) can correct the display anyway.  */
 32611       if (! cmp->font || cmp->font != font)
 32612         {
 32613           /* Ascent and descent of the font of the first character
 32614              of this composition (adjusted by baseline offset).
 32615              Ascent and descent of overall glyphs should not be less
 32616              than these, respectively.  */
 32617           int font_ascent, font_descent, font_height;
 32618           /* Bounding box of the overall glyphs.  */
 32619           int leftmost, rightmost, lowest, highest;
 32620           int lbearing, rbearing;
 32621           int i, width, ascent, descent;
 32622           int c;
 32623           unsigned char2b;
 32624           struct font_metrics *pcm;
 32625           ptrdiff_t pos;
 32626 
 32627           eassume (0 < glyph_len); /* See Bug#8512.  */
 32628           do
 32629             c = COMPOSITION_GLYPH (cmp, glyph_len - 1);
 32630           while (c == '\t' && 0 < --glyph_len);
 32631 
 32632           bool right_padded = glyph_len < cmp->glyph_len;
 32633           for (i = 0; i < glyph_len; i++)
 32634             {
 32635               c = COMPOSITION_GLYPH (cmp, i);
 32636               if (c != '\t')
 32637                 break;
 32638               cmp->offsets[i * 2] = cmp->offsets[i * 2 + 1] = 0;
 32639             }
 32640           bool left_padded = i > 0;
 32641 
 32642           pos = (STRINGP (it->string) ? IT_STRING_CHARPOS (*it)
 32643                  : IT_CHARPOS (*it));
 32644           /* If no suitable font is found, use the default font.  */
 32645           bool font_not_found_p = font == NULL;
 32646           if (font_not_found_p)
 32647             {
 32648               face = face->ascii_face;
 32649               font = face->font;
 32650             }
 32651           boff = font->baseline_offset;
 32652           if (font->vertical_centering)
 32653             boff = VCENTER_BASELINE_OFFSET (font, it->f) - boff;
 32654           normal_char_ascent_descent (font, -1, &font_ascent, &font_descent);
 32655           font_ascent +=  boff;
 32656           font_descent -= boff;
 32657           font_height = font_ascent + font_descent;
 32658 
 32659           cmp->font = font;
 32660 
 32661           pcm = NULL;
 32662           if (! font_not_found_p)
 32663             {
 32664               get_char_face_and_encoding (it->f, c, it->face_id,
 32665                                           &char2b, false);
 32666               pcm = get_per_char_metric (font, &char2b);
 32667             }
 32668 
 32669           /* Initialize the bounding box.  */
 32670           if (pcm)
 32671             {
 32672               width = cmp->glyph_len > 0 ? pcm->width : 0;
 32673               ascent = pcm->ascent;
 32674               descent = pcm->descent;
 32675               lbearing = pcm->lbearing;
 32676               rbearing = pcm->rbearing;
 32677             }
 32678           else
 32679             {
 32680               width = cmp->glyph_len > 0 ? font->space_width : 0;
 32681               ascent = FONT_BASE (font);
 32682               descent = FONT_DESCENT (font);
 32683               lbearing = 0;
 32684               rbearing = width;
 32685             }
 32686 
 32687           rightmost = width;
 32688           leftmost = 0;
 32689           lowest = - descent + boff;
 32690           highest = ascent + boff;
 32691 
 32692           if (! font_not_found_p
 32693               && font->default_ascent
 32694               && CHAR_TABLE_P (Vuse_default_ascent)
 32695               && !NILP (Faref (Vuse_default_ascent,
 32696                                make_fixnum (it->char_to_display))))
 32697             highest = font->default_ascent + boff;
 32698 
 32699           /* Draw the first glyph at the normal position.  It may be
 32700              shifted to right later if some other glyphs are drawn
 32701              at the left.  */
 32702           cmp->offsets[i * 2] = 0;
 32703           cmp->offsets[i * 2 + 1] = boff;
 32704           cmp->lbearing = lbearing;
 32705           cmp->rbearing = rbearing;
 32706 
 32707           /* Set cmp->offsets for the remaining glyphs.  */
 32708           for (i++; i < glyph_len; i++)
 32709             {
 32710               int left, right, btm, top;
 32711               int ch = COMPOSITION_GLYPH (cmp, i);
 32712               int face_id;
 32713               struct face *this_face;
 32714 
 32715               if (ch == '\t')
 32716                 ch = ' ';
 32717               face_id = FACE_FOR_CHAR (it->f, face, ch, pos, it->string);
 32718               this_face = FACE_FROM_ID (it->f, face_id);
 32719               font = this_face->font;
 32720 
 32721               if (font == NULL)
 32722                 pcm = NULL;
 32723               else
 32724                 {
 32725                   get_char_face_and_encoding (it->f, ch, face_id,
 32726                                               &char2b, false);
 32727                   pcm = get_per_char_metric (font, &char2b);
 32728                 }
 32729               if (! pcm)
 32730                 cmp->offsets[i * 2] = cmp->offsets[i * 2 + 1] = 0;
 32731               else
 32732                 {
 32733                   width = pcm->width;
 32734                   ascent = pcm->ascent;
 32735                   descent = pcm->descent;
 32736                   lbearing = pcm->lbearing;
 32737                   rbearing = pcm->rbearing;
 32738                   if (cmp->method != COMPOSITION_WITH_RULE_ALTCHARS)
 32739                     {
 32740                       /* Relative composition with or without
 32741                          alternate chars.  */
 32742                       left = (leftmost + rightmost - width) / 2;
 32743                       btm = - descent + boff;
 32744                       if (font->relative_compose
 32745                           && (! CHAR_TABLE_P (Vignore_relative_composition)
 32746                               || NILP (Faref (Vignore_relative_composition,
 32747                                               make_fixnum (ch)))))
 32748                         {
 32749 
 32750                           if (- descent >= font->relative_compose)
 32751                             /* One extra pixel between two glyphs.  */
 32752                             btm = highest + 1;
 32753                           else if (ascent <= 0)
 32754                             /* One extra pixel between two glyphs.  */
 32755                             btm = lowest - 1 - ascent - descent;
 32756                         }
 32757                     }
 32758                   else
 32759                     {
 32760                       /* A composition rule is specified by an integer
 32761                          value that encodes global and new reference
 32762                          points (GREF and NREF).  GREF and NREF are
 32763                          specified by numbers as below:
 32764 
 32765                          0---1---2 -- ascent
 32766                          |       |
 32767                          |       |
 32768                          |       |
 32769                          9--10--11 -- center
 32770                          |       |
 32771                          ---3---4---5--- baseline
 32772                          |       |
 32773                          6---7---8 -- descent
 32774                       */
 32775                       int rule = COMPOSITION_RULE (cmp, i);
 32776                       int gref, nref, grefx, grefy, nrefx, nrefy, xoff, yoff;
 32777 
 32778                       COMPOSITION_DECODE_RULE (rule, gref, nref, xoff, yoff);
 32779                       grefx = gref % 3, nrefx = nref % 3;
 32780                       grefy = gref / 3, nrefy = nref / 3;
 32781                       if (xoff)
 32782                         xoff = font_height * (xoff - 128) / 256;
 32783                       if (yoff)
 32784                         yoff = font_height * (yoff - 128) / 256;
 32785 
 32786                       left = (leftmost
 32787                               + grefx * (rightmost - leftmost) / 2
 32788                               - nrefx * width / 2
 32789                               + xoff);
 32790 
 32791                       btm = ((grefy == 0 ? highest
 32792                               : grefy == 1 ? 0
 32793                               : grefy == 2 ? lowest
 32794                               : (highest + lowest) / 2)
 32795                              - (nrefy == 0 ? ascent + descent
 32796                                 : nrefy == 1 ? descent - boff
 32797                                 : nrefy == 2 ? 0
 32798                                 : (ascent + descent) / 2)
 32799                              + yoff);
 32800                     }
 32801 
 32802                   cmp->offsets[i * 2] = left;
 32803                   cmp->offsets[i * 2 + 1] = btm + descent;
 32804 
 32805                   /* Update the bounding box of the overall glyphs. */
 32806                   if (width > 0)
 32807                     {
 32808                       right = left + width;
 32809                       if (left < leftmost)
 32810                         leftmost = left;
 32811                       if (right > rightmost)
 32812                         rightmost = right;
 32813                     }
 32814                   top = btm + descent + ascent;
 32815                   if (top > highest)
 32816                     highest = top;
 32817                   if (btm < lowest)
 32818                     lowest = btm;
 32819 
 32820                   if (cmp->lbearing > left + lbearing)
 32821                     cmp->lbearing = left + lbearing;
 32822                   if (cmp->rbearing < left + rbearing)
 32823                     cmp->rbearing = left + rbearing;
 32824                 }
 32825             }
 32826 
 32827           /* If there are glyphs whose x-offsets are negative,
 32828              shift all glyphs to the right and make all x-offsets
 32829              non-negative.  */
 32830           if (leftmost < 0)
 32831             {
 32832               for (i = 0; i < cmp->glyph_len; i++)
 32833                 cmp->offsets[i * 2] -= leftmost;
 32834               rightmost -= leftmost;
 32835               cmp->lbearing -= leftmost;
 32836               cmp->rbearing -= leftmost;
 32837             }
 32838 
 32839           if (left_padded && cmp->lbearing < 0)
 32840             {
 32841               for (i = 0; i < cmp->glyph_len; i++)
 32842                 cmp->offsets[i * 2] -= cmp->lbearing;
 32843               rightmost -= cmp->lbearing;
 32844               cmp->rbearing -= cmp->lbearing;
 32845               cmp->lbearing = 0;
 32846             }
 32847           if (right_padded && rightmost < cmp->rbearing)
 32848             {
 32849               rightmost = cmp->rbearing;
 32850             }
 32851 
 32852           cmp->pixel_width = rightmost;
 32853           cmp->ascent = highest;
 32854           cmp->descent = - lowest;
 32855           if (cmp->ascent < font_ascent)
 32856             cmp->ascent = font_ascent;
 32857           if (cmp->descent < font_descent)
 32858             cmp->descent = font_descent;
 32859         }
 32860 
 32861       if (it->glyph_row
 32862           && (cmp->lbearing < 0
 32863               || cmp->rbearing > cmp->pixel_width))
 32864         it->glyph_row->contains_overlapping_glyphs_p = true;
 32865 
 32866       it->pixel_width = cmp->pixel_width;
 32867       it->ascent = it->phys_ascent = cmp->ascent;
 32868       it->descent = it->phys_descent = cmp->descent;
 32869       IT_APPLY_FACE_BOX(it, face);
 32870 
 32871       /* If face has an overline, add the height of the overline
 32872          (1 pixel) and a 1 pixel margin to the character height.  */
 32873       if (face->overline_p)
 32874         it->ascent += clip_to_bounds (0, overline_margin, 1000000);
 32875 
 32876       take_vertical_position_into_account (it);
 32877       if (it->ascent < 0)
 32878         it->ascent = 0;
 32879       if (it->descent < 0)
 32880         it->descent = 0;
 32881 
 32882       if (it->glyph_row && cmp->glyph_len > 0)
 32883         append_composite_glyph (it);
 32884     }
 32885   else if (it->what == IT_COMPOSITION)
 32886     {
 32887       /* A dynamic (automatic) composition.  */
 32888       struct face *face = FACE_FROM_ID (it->f, it->face_id);
 32889       Lisp_Object gstring;
 32890       struct font_metrics metrics;
 32891 
 32892       it->nglyphs = 1;
 32893 
 32894       gstring = composition_gstring_from_id (it->cmp_it.id);
 32895       it->pixel_width
 32896         = composition_gstring_width (gstring, it->cmp_it.from, it->cmp_it.to,
 32897                                      &metrics);
 32898       if (it->pixel_width == 0)
 32899         {
 32900           it->glyph_not_available_p = true;
 32901           it->phys_ascent = it->ascent;
 32902           it->phys_descent = it->descent;
 32903           it->pixel_width = face->font->space_width;
 32904         }
 32905       else
 32906         {
 32907           if (it->glyph_row
 32908               && (metrics.lbearing < 0 || metrics.rbearing > metrics.width))
 32909             it->glyph_row->contains_overlapping_glyphs_p = true;
 32910           it->ascent = it->phys_ascent = metrics.ascent;
 32911           it->descent = it->phys_descent = metrics.descent;
 32912         }
 32913       IT_APPLY_FACE_BOX(it, face);
 32914 
 32915       /* If face has an overline, add the height of the overline
 32916          (1 pixel) and a 1 pixel margin to the character height.  */
 32917       if (face->overline_p)
 32918         it->ascent += clip_to_bounds (0, overline_margin, 1000000);
 32919       take_vertical_position_into_account (it);
 32920       if (it->ascent < 0)
 32921         it->ascent = 0;
 32922       if (it->descent < 0)
 32923         it->descent = 0;
 32924 
 32925       if (it->glyph_row)
 32926         append_composite_glyph (it);
 32927     }
 32928   else if (it->what == IT_GLYPHLESS)
 32929     produce_glyphless_glyph (it, false, Qnil);
 32930   else if (it->what == IT_IMAGE)
 32931     produce_image_glyph (it);
 32932   else if (it->what == IT_STRETCH)
 32933     produce_stretch_glyph (it);
 32934   else if (it->what == IT_XWIDGET)
 32935     produce_xwidget_glyph (it);
 32936 
 32937  done:
 32938   /* Accumulate dimensions.  Note: can't assume that it->descent > 0
 32939      because this isn't true for images with `:ascent 100'.  */
 32940   eassert (it->ascent >= 0 && it->descent >= 0);
 32941   if (it->area == TEXT_AREA)
 32942     it->current_x += it->pixel_width;
 32943 
 32944   if (extra_line_spacing > 0)
 32945     {
 32946       it->descent += extra_line_spacing;
 32947       if (extra_line_spacing > it->max_extra_line_spacing)
 32948         it->max_extra_line_spacing = extra_line_spacing;
 32949     }
 32950 
 32951   it->max_ascent = max (it->max_ascent, it->ascent);
 32952   it->max_descent = max (it->max_descent, it->descent);
 32953   it->max_phys_ascent = max (it->max_phys_ascent, it->phys_ascent);
 32954   it->max_phys_descent = max (it->max_phys_descent, it->phys_descent);
 32955 }
 32956 
 32957 /* EXPORT for RIF:
 32958    Output LEN glyphs starting at START at the nominal cursor position.
 32959    Advance the nominal cursor over the text.  UPDATED_ROW is the glyph row
 32960    being updated, and UPDATED_AREA is the area of that row being updated.  */
 32961 
 32962 void
 32963 gui_write_glyphs (struct window *w, struct glyph_row *updated_row,
 32964                 struct glyph *start, enum glyph_row_area updated_area, int len)
 32965 {
 32966   int x, hpos, chpos = w->phys_cursor.hpos;
 32967 
 32968   eassert (updated_row);
 32969   /* When the window is hscrolled, cursor hpos can legitimately be out
 32970      of bounds, but we draw the cursor at the corresponding window
 32971      margin in that case.  */
 32972   if (!updated_row->reversed_p && chpos < 0)
 32973     chpos = 0;
 32974   if (updated_row->reversed_p && chpos >= updated_row->used[TEXT_AREA])
 32975     chpos = updated_row->used[TEXT_AREA] - 1;
 32976 
 32977   block_input ();
 32978 
 32979   /* Write glyphs.  */
 32980 
 32981   hpos = start - updated_row->glyphs[updated_area];
 32982   x = draw_glyphs (w, w->output_cursor.x,
 32983                    updated_row, updated_area,
 32984                    hpos, hpos + len,
 32985                    DRAW_NORMAL_TEXT, 0);
 32986 
 32987   /* Invalidate old phys cursor if the glyph at its hpos is redrawn.  */
 32988   if (updated_area == TEXT_AREA
 32989       && w->phys_cursor_on_p
 32990       && w->phys_cursor.vpos == w->output_cursor.vpos
 32991       && chpos >= hpos
 32992       && chpos < hpos + len)
 32993     w->phys_cursor_on_p = false;
 32994 
 32995   unblock_input ();
 32996 
 32997   /* Advance the output cursor.  */
 32998   w->output_cursor.hpos += len;
 32999   w->output_cursor.x = x;
 33000 }
 33001 
 33002 
 33003 /* EXPORT for RIF:
 33004    Insert LEN glyphs from START at the nominal cursor position.  */
 33005 
 33006 void
 33007 gui_insert_glyphs (struct window *w, struct glyph_row *updated_row,
 33008                  struct glyph *start, enum glyph_row_area updated_area, int len)
 33009 {
 33010   struct frame *f;
 33011   int line_height, shift_by_width, shifted_region_width;
 33012   struct glyph_row *row;
 33013   struct glyph *glyph;
 33014   int frame_x, frame_y;
 33015   ptrdiff_t hpos;
 33016 
 33017   eassert (updated_row);
 33018   block_input ();
 33019   f = XFRAME (WINDOW_FRAME (w));
 33020 
 33021   /* Get the height of the line we are in.  */
 33022   row = updated_row;
 33023   line_height = row->height;
 33024 
 33025   /* Get the width of the glyphs to insert.  */
 33026   shift_by_width = 0;
 33027   for (glyph = start; glyph < start + len; ++glyph)
 33028     shift_by_width += glyph->pixel_width;
 33029 
 33030   /* Get the width of the region to shift right.  */
 33031   shifted_region_width = (window_box_width (w, updated_area)
 33032                           - w->output_cursor.x
 33033                           - shift_by_width);
 33034 
 33035   /* Shift right.  */
 33036   frame_x = window_box_left (w, updated_area) + w->output_cursor.x;
 33037   frame_y = WINDOW_TO_FRAME_PIXEL_Y (w, w->output_cursor.y);
 33038 
 33039   FRAME_RIF (f)->shift_glyphs_for_insert (f, frame_x, frame_y, shifted_region_width,
 33040                                           line_height, shift_by_width);
 33041 
 33042   /* Write the glyphs.  */
 33043   hpos = start - row->glyphs[updated_area];
 33044   draw_glyphs (w, w->output_cursor.x, row, updated_area,
 33045                hpos, hpos + len,
 33046                DRAW_NORMAL_TEXT, 0);
 33047 
 33048   /* Advance the output cursor.  */
 33049   w->output_cursor.hpos += len;
 33050   w->output_cursor.x += shift_by_width;
 33051   unblock_input ();
 33052 }
 33053 
 33054 
 33055 /* EXPORT for RIF:
 33056    Erase the current text line from the nominal cursor position
 33057    (inclusive) to pixel column TO_X (exclusive).  The idea is that
 33058    everything from TO_X onward is already erased.
 33059 
 33060    TO_X is a pixel position relative to UPDATED_AREA of currently
 33061    updated window W.  TO_X == -1 means clear to the end of this area.  */
 33062 
 33063 void
 33064 gui_clear_end_of_line (struct window *w, struct glyph_row *updated_row,
 33065                        enum glyph_row_area updated_area, int to_x)
 33066 {
 33067   struct frame *f;
 33068   int max_x, min_y, max_y;
 33069   int from_x, from_y, to_y;
 33070   struct face *face;
 33071 
 33072   eassert (updated_row);
 33073   f = XFRAME (w->frame);
 33074   face = FACE_FROM_ID_OR_NULL (f, DEFAULT_FACE_ID);
 33075 
 33076   if (updated_row->full_width_p)
 33077     max_x = (WINDOW_PIXEL_WIDTH (w)
 33078              - (updated_row->mode_line_p ? WINDOW_RIGHT_DIVIDER_WIDTH (w) : 0));
 33079   else
 33080     max_x = window_box_width (w, updated_area);
 33081   max_y = window_text_bottom_y (w);
 33082 
 33083   /* TO_X == 0 means don't do anything.  TO_X < 0 means clear to end
 33084      of window.  For TO_X > 0, truncate to end of drawing area.  */
 33085   if (to_x == 0)
 33086     return;
 33087   else if (to_x < 0)
 33088     to_x = max_x;
 33089   else
 33090     to_x = min (to_x, max_x);
 33091 
 33092   to_y = min (max_y, w->output_cursor.y + updated_row->height);
 33093 
 33094   /* Notice if the cursor will be cleared by this operation.  */
 33095   if (!updated_row->full_width_p)
 33096     notice_overwritten_cursor (w, updated_area,
 33097                                w->output_cursor.x, -1,
 33098                                updated_row->y,
 33099                                MATRIX_ROW_BOTTOM_Y (updated_row));
 33100 
 33101   from_x = w->output_cursor.x;
 33102 
 33103   /* Translate to frame coordinates.  */
 33104   if (updated_row->full_width_p)
 33105     {
 33106       from_x = WINDOW_TO_FRAME_PIXEL_X (w, from_x);
 33107       to_x = WINDOW_TO_FRAME_PIXEL_X (w, to_x);
 33108     }
 33109   else
 33110     {
 33111       int area_left = window_box_left (w, updated_area);
 33112       from_x += area_left;
 33113       to_x += area_left;
 33114     }
 33115 
 33116   min_y = WINDOW_TAB_LINE_HEIGHT (w) + WINDOW_HEADER_LINE_HEIGHT (w);
 33117   from_y = WINDOW_TO_FRAME_PIXEL_Y (w, max (min_y, w->output_cursor.y));
 33118   to_y = WINDOW_TO_FRAME_PIXEL_Y (w, to_y);
 33119 
 33120   /* Prevent inadvertently clearing to end of the X window.  */
 33121   if (to_x > from_x && to_y > from_y)
 33122     {
 33123       block_input ();
 33124       FRAME_RIF (f)->clear_frame_area (f, from_x, from_y,
 33125                                        to_x - from_x, to_y - from_y);
 33126 
 33127       if (face && !updated_row->stipple_p)
 33128         updated_row->stipple_p = face->stipple;
 33129       unblock_input ();
 33130     }
 33131 }
 33132 
 33133 #endif /* HAVE_WINDOW_SYSTEM */
 33134 
 33135 
 33136 
 33137 /***********************************************************************
 33138                              Cursor types
 33139  ***********************************************************************/
 33140 
 33141 /* Value is the internal representation of the specified cursor type
 33142    ARG.  If type is BAR_CURSOR, return in *WIDTH the specified width
 33143    of the bar cursor.  */
 33144 
 33145 static enum text_cursor_kinds
 33146 get_specified_cursor_type (Lisp_Object arg, int *width)
 33147 {
 33148   enum text_cursor_kinds type;
 33149 
 33150   if (NILP (arg))
 33151     return NO_CURSOR;
 33152 
 33153   if (EQ (arg, Qbox))
 33154     return FILLED_BOX_CURSOR;
 33155 
 33156   if (EQ (arg, Qhollow))
 33157     return HOLLOW_BOX_CURSOR;
 33158 
 33159   if (EQ (arg, Qbar))
 33160     {
 33161       *width = 2;
 33162       return BAR_CURSOR;
 33163     }
 33164 
 33165   if (EQ (arg, Qhbar))
 33166     {
 33167       *width = 2;
 33168       return HBAR_CURSOR;
 33169     }
 33170 
 33171   if (CONSP (arg)
 33172       && RANGED_FIXNUMP (0, XCDR (arg), INT_MAX))
 33173     {
 33174       *width = XFIXNUM (XCDR (arg));
 33175 
 33176       if (EQ (XCAR (arg), Qbox))
 33177           return FILLED_BOX_CURSOR;
 33178       else if (EQ (XCAR (arg), Qbar))
 33179           return BAR_CURSOR;
 33180       else if (EQ (XCAR (arg), Qhbar))
 33181           return HBAR_CURSOR;
 33182     }
 33183 
 33184   /* Treat anything unknown as "hollow box cursor".
 33185      It was bad to signal an error; people have trouble fixing
 33186      .Xdefaults with Emacs, when it has something bad in it.  */
 33187   type = HOLLOW_BOX_CURSOR;
 33188 
 33189   return type;
 33190 }
 33191 
 33192 /* Set the default cursor types for specified frame.  */
 33193 void
 33194 set_frame_cursor_types (struct frame *f, Lisp_Object arg)
 33195 {
 33196   int width = 1;
 33197   Lisp_Object tem;
 33198 
 33199   FRAME_DESIRED_CURSOR (f) = get_specified_cursor_type (arg, &width);
 33200   FRAME_CURSOR_WIDTH (f) = width;
 33201 
 33202   /* By default, set up the blink-off state depending on the on-state.  */
 33203 
 33204   tem = Fassoc (arg, Vblink_cursor_alist, Qnil);
 33205   if (!NILP (tem))
 33206     {
 33207       FRAME_BLINK_OFF_CURSOR (f)
 33208         = get_specified_cursor_type (XCDR (tem), &width);
 33209       FRAME_BLINK_OFF_CURSOR_WIDTH (f) = width;
 33210     }
 33211   else
 33212     FRAME_BLINK_OFF_CURSOR (f) = DEFAULT_CURSOR;
 33213 
 33214   /* Make sure the cursor gets redrawn.  */
 33215   f->cursor_type_changed = true;
 33216 }
 33217 
 33218 
 33219 #ifdef HAVE_WINDOW_SYSTEM
 33220 
 33221 /* Return the cursor we want to be displayed in window W.  Return
 33222    width of bar/hbar cursor through WIDTH arg.  Return with
 33223    ACTIVE_CURSOR arg set to true if cursor in window W is `active'
 33224    (i.e. if the `system caret' should track this cursor).
 33225 
 33226    In a mini-buffer window, we want the cursor only to appear if we
 33227    are reading input from this window.  For the selected window, we
 33228    want the cursor type given by the frame parameter or buffer local
 33229    setting of cursor-type.  If explicitly marked off, draw no cursor.
 33230    In all other cases, we want a hollow box cursor.  */
 33231 
 33232 static enum text_cursor_kinds
 33233 get_window_cursor_type (struct window *w, struct glyph *glyph, int *width,
 33234                         bool *active_cursor)
 33235 {
 33236   struct frame *f = XFRAME (w->frame);
 33237   struct buffer *b = XBUFFER (w->contents);
 33238   int cursor_type = DEFAULT_CURSOR;
 33239   Lisp_Object alt_cursor;
 33240   bool non_selected = false;
 33241 
 33242   *active_cursor = true;
 33243 
 33244   /* Echo area */
 33245   if (cursor_in_echo_area
 33246       && FRAME_HAS_MINIBUF_P (f)
 33247       && EQ (FRAME_MINIBUF_WINDOW (f), echo_area_window))
 33248     {
 33249       if (w == XWINDOW (echo_area_window))
 33250         {
 33251           if (EQ (BVAR (b, cursor_type), Qt) || NILP (BVAR (b, cursor_type)))
 33252             {
 33253               *width = FRAME_CURSOR_WIDTH (f);
 33254               return FRAME_DESIRED_CURSOR (f);
 33255             }
 33256           else
 33257             return get_specified_cursor_type (BVAR (b, cursor_type), width);
 33258         }
 33259 
 33260       *active_cursor = false;
 33261       non_selected = true;
 33262     }
 33263 
 33264   /* Detect a nonselected window or nonselected frame.  */
 33265   else if (w != XWINDOW (f->selected_window)
 33266            || f != FRAME_DISPLAY_INFO (f)->highlight_frame)
 33267     {
 33268       *active_cursor = false;
 33269 
 33270       if (MINI_WINDOW_P (w) &&
 33271           (minibuf_level == 0
 33272            || is_minibuffer (0, w->contents)))
 33273         return NO_CURSOR;
 33274 
 33275       non_selected = true;
 33276     }
 33277 
 33278   /* Never display a cursor in a window in which cursor-type is nil.  */
 33279   if (NILP (BVAR (b, cursor_type)))
 33280     return NO_CURSOR;
 33281 
 33282   /* Get the normal cursor type for this window.  */
 33283   if (EQ (BVAR (b, cursor_type), Qt))
 33284     {
 33285       cursor_type = FRAME_DESIRED_CURSOR (f);
 33286       *width = FRAME_CURSOR_WIDTH (f);
 33287     }
 33288   else
 33289     cursor_type = get_specified_cursor_type (BVAR (b, cursor_type), width);
 33290 
 33291   /* Use cursor-in-non-selected-windows instead
 33292      for non-selected window or frame.  */
 33293   if (non_selected)
 33294     {
 33295       alt_cursor = BVAR (b, cursor_in_non_selected_windows);
 33296       if (!EQ (Qt, alt_cursor))
 33297         return get_specified_cursor_type (alt_cursor, width);
 33298       /* t means modify the normal cursor type.  */
 33299       if (cursor_type == FILLED_BOX_CURSOR)
 33300         cursor_type = HOLLOW_BOX_CURSOR;
 33301       else if (cursor_type == BAR_CURSOR && *width > 1)
 33302         --*width;
 33303       return cursor_type;
 33304     }
 33305 
 33306   /* Use normal cursor if not blinked off.  */
 33307   if (!w->cursor_off_p)
 33308     {
 33309       if (glyph != NULL && glyph->type == XWIDGET_GLYPH)
 33310         return NO_CURSOR;
 33311       if (glyph != NULL && glyph->type == IMAGE_GLYPH)
 33312         {
 33313           if (cursor_type == FILLED_BOX_CURSOR)
 33314             {
 33315               /* Using a block cursor on large images can be very
 33316                  annoying.  So use a hollow cursor for "large" images.
 33317                  If image is not transparent (no mask), also use
 33318                  hollow cursor.  */
 33319               struct image *img = IMAGE_OPT_FROM_ID (f, glyph->u.img_id);
 33320               if (img != NULL && IMAGEP (img->spec))
 33321                 {
 33322                   /* Interpret "large" as >SIZExSIZE and >NxN where
 33323                      SIZE is the value from cursor-type of the form
 33324                      (box . SIZE), where N = size of default frame
 33325                      font size.  So, setting cursor-type to (box . 32)
 33326                      should cover most of the "tiny" icons people may
 33327                      use.  */
 33328                   if (!img->mask
 33329                       || (CONSP (BVAR (b, cursor_type))
 33330                           && img->width > max (*width, WINDOW_FRAME_COLUMN_WIDTH (w))
 33331                           && img->height > max (*width, WINDOW_FRAME_LINE_HEIGHT (w))))
 33332                     cursor_type = HOLLOW_BOX_CURSOR;
 33333                 }
 33334             }
 33335           else if (cursor_type != NO_CURSOR)
 33336             {
 33337               /* Display current only supports BOX and HOLLOW cursors for images.
 33338                  So for now, unconditionally use a HOLLOW cursor when cursor is
 33339                  not a solid box cursor.  */
 33340               cursor_type = HOLLOW_BOX_CURSOR;
 33341             }
 33342       }
 33343       return cursor_type;
 33344     }
 33345 
 33346   /* Cursor is blinked off, so determine how to "toggle" it.  */
 33347 
 33348   /* First look for an entry matching the buffer's cursor-type in blink-cursor-alist.  */
 33349   if ((alt_cursor = Fassoc (BVAR (b, cursor_type), Vblink_cursor_alist, Qnil), !NILP (alt_cursor)))
 33350     return get_specified_cursor_type (XCDR (alt_cursor), width);
 33351 
 33352   /* Then see if frame has specified a specific blink off cursor type.  */
 33353   if (FRAME_BLINK_OFF_CURSOR (f) != DEFAULT_CURSOR)
 33354     {
 33355       *width = FRAME_BLINK_OFF_CURSOR_WIDTH (f);
 33356       return FRAME_BLINK_OFF_CURSOR (f);
 33357     }
 33358 
 33359 #if false
 33360   /* Some people liked having a permanently visible blinking cursor,
 33361      while others had very strong opinions against it.  So it was
 33362      decided to remove it.  KFS 2003-09-03 */
 33363 
 33364   /* Finally perform built-in cursor blinking:
 33365        filled box      <->   hollow box
 33366        wide [h]bar     <->   narrow [h]bar
 33367        narrow [h]bar   <->   no cursor
 33368        other type      <->   no cursor  */
 33369 
 33370   if (cursor_type == FILLED_BOX_CURSOR)
 33371     return HOLLOW_BOX_CURSOR;
 33372 
 33373   if ((cursor_type == BAR_CURSOR || cursor_type == HBAR_CURSOR) && *width > 1)
 33374     {
 33375       *width = 1;
 33376       return cursor_type;
 33377     }
 33378 #endif
 33379 
 33380   return NO_CURSOR;
 33381 }
 33382 
 33383 
 33384 /* Notice when the text cursor of window W has been completely
 33385    overwritten by a drawing operation that outputs glyphs in AREA
 33386    starting at X0 and ending at X1 in the line starting at Y0 and
 33387    ending at Y1.  X coordinates are area-relative.  X1 < 0 means all
 33388    the rest of the line after X0 has been written.  Y coordinates
 33389    are window-relative.  */
 33390 
 33391 static void
 33392 notice_overwritten_cursor (struct window *w, enum glyph_row_area area,
 33393                            int x0, int x1, int y0, int y1)
 33394 {
 33395   int cx0, cx1, cy0, cy1;
 33396   struct glyph_row *row;
 33397 
 33398   if (!w->phys_cursor_on_p)
 33399     return;
 33400   if (area != TEXT_AREA)
 33401     return;
 33402 
 33403   if (w->phys_cursor.vpos < 0
 33404       || w->phys_cursor.vpos >= w->current_matrix->nrows
 33405       || (row = w->current_matrix->rows + w->phys_cursor.vpos,
 33406           !(row->enabled_p && MATRIX_ROW_DISPLAYS_TEXT_P (row))))
 33407     return;
 33408 
 33409   if (row->cursor_in_fringe_p)
 33410     {
 33411       row->cursor_in_fringe_p = false;
 33412       draw_fringe_bitmap (w, row, row->reversed_p);
 33413       w->phys_cursor_on_p = false;
 33414       return;
 33415     }
 33416 
 33417   cx0 = w->phys_cursor.x;
 33418   cx1 = cx0 + w->phys_cursor_width;
 33419   if (x0 > cx0 || (x1 >= 0 && x1 < cx1))
 33420     return;
 33421 
 33422   /* The cursor image will be completely removed from the
 33423      screen if the output area intersects the cursor area in
 33424      y-direction.  When we draw in [y0 y1[, and some part of
 33425      the cursor is at y < y0, that part must have been drawn
 33426      before.  When scrolling, the cursor is erased before
 33427      actually scrolling, so we don't come here.  When not
 33428      scrolling, the rows above the old cursor row must have
 33429      changed, and in this case these rows must have written
 33430      over the cursor image.
 33431 
 33432      Likewise if part of the cursor is below y1, with the
 33433      exception of the cursor being in the first blank row at
 33434      the buffer and window end because update_text_area
 33435      doesn't draw that row.  (Except when it does, but
 33436      that's handled in update_text_area.)  */
 33437 
 33438   cy0 = w->phys_cursor.y;
 33439   cy1 = cy0 + w->phys_cursor_height;
 33440   if ((y0 < cy0 || y0 >= cy1) && (y1 <= cy0 || y1 >= cy1))
 33441     return;
 33442 
 33443   w->phys_cursor_on_p = false;
 33444 }
 33445 
 33446 #endif /* HAVE_WINDOW_SYSTEM */
 33447 
 33448 
 33449 /************************************************************************
 33450                               Mouse Face
 33451  ************************************************************************/
 33452 
 33453 #ifdef HAVE_WINDOW_SYSTEM
 33454 
 33455 /* EXPORT for RIF:
 33456    Fix the display of area AREA of overlapping row ROW in window W
 33457    with respect to the overlapping part OVERLAPS.  */
 33458 
 33459 void
 33460 gui_fix_overlapping_area (struct window *w, struct glyph_row *row,
 33461                         enum glyph_row_area area, int overlaps)
 33462 {
 33463   int i, x;
 33464 
 33465   block_input ();
 33466 
 33467   x = 0;
 33468   for (i = 0; i < row->used[area];)
 33469     {
 33470       if (row->glyphs[area][i].overlaps_vertically_p)
 33471         {
 33472           int start = i, start_x = x;
 33473 
 33474           do
 33475             {
 33476               x += row->glyphs[area][i].pixel_width;
 33477               ++i;
 33478             }
 33479           while (i < row->used[area]
 33480                  && row->glyphs[area][i].overlaps_vertically_p);
 33481 
 33482           draw_glyphs (w, start_x, row, area,
 33483                        start, i,
 33484                        DRAW_NORMAL_TEXT, overlaps);
 33485         }
 33486       else
 33487         {
 33488           x += row->glyphs[area][i].pixel_width;
 33489           ++i;
 33490         }
 33491     }
 33492 
 33493   unblock_input ();
 33494 }
 33495 
 33496 
 33497 /* EXPORT:
 33498    Draw the cursor glyph of window W in glyph row ROW.  See the
 33499    comment of draw_glyphs for the meaning of HL.  */
 33500 
 33501 void
 33502 draw_phys_cursor_glyph (struct window *w, struct glyph_row *row,
 33503                         enum draw_glyphs_face hl)
 33504 {
 33505   /* If cursor hpos is out of bounds, don't draw garbage.  This can
 33506      happen in mini-buffer windows when switching between echo area
 33507      glyphs and mini-buffer.  */
 33508   if ((row->reversed_p
 33509        ? (w->phys_cursor.hpos >= 0)
 33510        : (w->phys_cursor.hpos < row->used[TEXT_AREA])))
 33511     {
 33512       bool on_p = w->phys_cursor_on_p;
 33513       int x1;
 33514       int hpos = w->phys_cursor.hpos;
 33515 
 33516       /* When the window is hscrolled, cursor hpos can legitimately be
 33517          out of bounds, but we draw the cursor at the corresponding
 33518          window margin in that case.  */
 33519       if (!row->reversed_p && hpos < 0)
 33520         hpos = 0;
 33521       if (row->reversed_p && hpos >= row->used[TEXT_AREA])
 33522         hpos = row->used[TEXT_AREA] - 1;
 33523 
 33524       x1 = draw_glyphs (w, w->phys_cursor.x, row, TEXT_AREA, hpos, hpos + 1,
 33525                         hl, 0);
 33526       w->phys_cursor_on_p = on_p;
 33527 
 33528       if (hl == DRAW_CURSOR)
 33529         w->phys_cursor_width = x1 - w->phys_cursor.x;
 33530       /* When we erase the cursor, and ROW is overlapped by other
 33531          rows, make sure that these overlapping parts of other rows
 33532          are redrawn.  */
 33533       else if (hl == DRAW_NORMAL_TEXT && row->overlapped_p)
 33534         {
 33535           w->phys_cursor_width = x1 - w->phys_cursor.x;
 33536 
 33537           if (row > w->current_matrix->rows
 33538               && MATRIX_ROW_OVERLAPS_SUCC_P (row - 1))
 33539             gui_fix_overlapping_area (w, row - 1, TEXT_AREA,
 33540                                     OVERLAPS_ERASED_CURSOR);
 33541 
 33542           if (MATRIX_ROW_BOTTOM_Y (row) < window_text_bottom_y (w)
 33543               && MATRIX_ROW_OVERLAPS_PRED_P (row + 1))
 33544             gui_fix_overlapping_area (w, row + 1, TEXT_AREA,
 33545                                     OVERLAPS_ERASED_CURSOR);
 33546         }
 33547     }
 33548 }
 33549 
 33550 
 33551 /* Erase the image of a cursor of window W from the screen.  */
 33552 
 33553 void
 33554 erase_phys_cursor (struct window *w)
 33555 {
 33556   struct frame *f = XFRAME (w->frame);
 33557   Mouse_HLInfo *hlinfo = MOUSE_HL_INFO (f);
 33558   int hpos = w->phys_cursor.hpos;
 33559   int vpos = w->phys_cursor.vpos;
 33560   bool mouse_face_here_p = false;
 33561   struct glyph_matrix *active_glyphs = w->current_matrix;
 33562   struct glyph_row *cursor_row;
 33563   struct glyph *cursor_glyph;
 33564   enum draw_glyphs_face hl;
 33565 
 33566   /* No cursor displayed or row invalidated => nothing to do on the
 33567      screen.  */
 33568   if (w->phys_cursor_type == NO_CURSOR)
 33569     goto mark_cursor_off;
 33570 
 33571   /* VPOS >= active_glyphs->nrows means that window has been resized.
 33572      Don't bother to erase the cursor.  */
 33573   if (vpos >= active_glyphs->nrows)
 33574     goto mark_cursor_off;
 33575 
 33576   /* If row containing cursor is marked invalid, there is nothing we
 33577      can do.  */
 33578   cursor_row = MATRIX_ROW (active_glyphs, vpos);
 33579   if (!cursor_row->enabled_p)
 33580     goto mark_cursor_off;
 33581 
 33582   /* If line spacing is > 0, old cursor may only be partially visible in
 33583      window after split-window.  So adjust visible height.  */
 33584   cursor_row->visible_height = min (cursor_row->visible_height,
 33585                                     window_text_bottom_y (w) - cursor_row->y);
 33586 
 33587   /* If row is completely invisible, don't attempt to delete a cursor which
 33588      isn't there.  This can happen if cursor is at top of a window, and
 33589      we switch to a buffer with a header line in that window.  */
 33590   if (cursor_row->visible_height <= 0)
 33591     goto mark_cursor_off;
 33592 
 33593   /* If cursor is in the fringe, erase by drawing actual bitmap there.  */
 33594   if (cursor_row->cursor_in_fringe_p)
 33595     {
 33596       cursor_row->cursor_in_fringe_p = false;
 33597       draw_fringe_bitmap (w, cursor_row, cursor_row->reversed_p);
 33598       goto mark_cursor_off;
 33599     }
 33600 
 33601   /* This can happen when the new row is shorter than the old one.
 33602      In this case, either draw_glyphs or clear_end_of_line
 33603      should have cleared the cursor.  Note that we wouldn't be
 33604      able to erase the cursor in this case because we don't have a
 33605      cursor glyph at hand.  */
 33606   if ((cursor_row->reversed_p
 33607        ? (w->phys_cursor.hpos < 0)
 33608        : (w->phys_cursor.hpos >= cursor_row->used[TEXT_AREA])))
 33609     goto mark_cursor_off;
 33610 
 33611   /* When the window is hscrolled, cursor hpos can legitimately be out
 33612      of bounds, but we draw the cursor at the corresponding window
 33613      margin in that case.  */
 33614   if (!cursor_row->reversed_p && hpos < 0)
 33615     hpos = 0;
 33616   if (cursor_row->reversed_p && hpos >= cursor_row->used[TEXT_AREA])
 33617     hpos = cursor_row->used[TEXT_AREA] - 1;
 33618 
 33619   /* If the cursor is in the mouse face area, redisplay that when
 33620      we clear the cursor.  */
 33621   if (! NILP (hlinfo->mouse_face_window)
 33622       && coords_in_mouse_face_p (w, hpos, vpos)
 33623       /* Don't redraw the cursor's spot in mouse face if it is at the
 33624          end of a line (on a newline).  The cursor appears there, but
 33625          mouse highlighting does not.  */
 33626       && cursor_row->used[TEXT_AREA] > hpos && hpos >= 0)
 33627     mouse_face_here_p = true;
 33628 
 33629 #ifdef HAVE_WINDOW_SYSTEM
 33630   /* Since erasing the phys cursor will probably lead to corruption of
 33631      the mouse face display if the glyph's pixel_width is not kept up
 33632      to date with the :box property of the mouse face, just redraw the
 33633      mouse face.  */
 33634   if (FRAME_WINDOW_P (WINDOW_XFRAME (w)) && mouse_face_here_p)
 33635     {
 33636       w->phys_cursor_on_p = false;
 33637       w->phys_cursor_type = NO_CURSOR;
 33638       show_mouse_face (MOUSE_HL_INFO (WINDOW_XFRAME (w)), DRAW_MOUSE_FACE);
 33639       return;
 33640     }
 33641 #endif
 33642 
 33643   /* Maybe clear the display under the cursor.  */
 33644   if (w->phys_cursor_type == HOLLOW_BOX_CURSOR)
 33645     {
 33646       int x, y;
 33647       int tab_line_height = WINDOW_TAB_LINE_HEIGHT (w);
 33648       int header_line_height = WINDOW_HEADER_LINE_HEIGHT (w);
 33649       int width;
 33650 
 33651       cursor_glyph = get_phys_cursor_glyph (w);
 33652       if (cursor_glyph == NULL)
 33653         goto mark_cursor_off;
 33654 
 33655       width = cursor_glyph->pixel_width;
 33656       x = w->phys_cursor.x;
 33657       if (x < 0)
 33658         {
 33659           width += x;
 33660           x = 0;
 33661         }
 33662       width = min (width, window_box_width (w, TEXT_AREA) - x);
 33663       y = WINDOW_TO_FRAME_PIXEL_Y (w, max (tab_line_height, max (header_line_height, cursor_row->y)));
 33664       x = WINDOW_TEXT_TO_FRAME_PIXEL_X (w, x);
 33665 
 33666       if (width > 0)
 33667         FRAME_RIF (f)->clear_frame_area (f, x, y, width, cursor_row->visible_height);
 33668     }
 33669 
 33670   /* Erase the cursor by redrawing the character underneath it.  */
 33671   if (mouse_face_here_p)
 33672     hl = DRAW_MOUSE_FACE;
 33673   else
 33674     hl = DRAW_NORMAL_TEXT;
 33675   draw_phys_cursor_glyph (w, cursor_row, hl);
 33676 
 33677  mark_cursor_off:
 33678   w->phys_cursor_on_p = false;
 33679   w->phys_cursor_type = NO_CURSOR;
 33680 }
 33681 
 33682 
 33683 /* Display or clear cursor of window W.  If !ON, clear the cursor.
 33684    If ON, display the cursor; where to put the cursor is specified by
 33685    HPOS, VPOS, X and Y.  */
 33686 
 33687 void
 33688 display_and_set_cursor (struct window *w, bool on,
 33689                         int hpos, int vpos, int x, int y)
 33690 {
 33691   struct frame *f = XFRAME (w->frame);
 33692   int new_cursor_type;
 33693   int new_cursor_width UNINIT;
 33694   bool active_cursor;
 33695   struct glyph_row *glyph_row;
 33696   struct glyph *glyph;
 33697 
 33698   /* This is pointless on invisible frames, and dangerous on garbaged
 33699      windows and frames; in the latter case, the frame or window may
 33700      be in the midst of changing its size, and x and y may be off the
 33701      window.  */
 33702   if (! FRAME_REDISPLAY_P (f)
 33703       || vpos >= w->current_matrix->nrows
 33704       || hpos >= w->current_matrix->matrix_w)
 33705     return;
 33706 
 33707   /* If cursor is off and we want it off, return quickly.  */
 33708   if (!on && !w->phys_cursor_on_p)
 33709     return;
 33710 
 33711   glyph_row = MATRIX_ROW (w->current_matrix, vpos);
 33712   /* If cursor row is not enabled, we don't really know where to
 33713      display the cursor.  */
 33714   if (!glyph_row->enabled_p)
 33715     {
 33716       w->phys_cursor_on_p = false;
 33717       return;
 33718     }
 33719 
 33720   /* A frame might be marked garbaged even though its cursor position
 33721      is correct, and will not change upon subsequent redisplay.  This
 33722      happens in some rare situations, like toggling the sort order in
 33723      Dired windows.  We've already established that VPOS is valid, so
 33724      it shouldn't do any harm to record the cursor position, as we are
 33725      going to return without acting on it anyway.  Otherwise, expose
 33726      events might come in and call update_window_cursor, which will
 33727      blindly use outdated values in w->phys_cursor.  */
 33728   if (FRAME_GARBAGED_P (f))
 33729     {
 33730       if (on)
 33731         {
 33732           w->phys_cursor.x = x;
 33733           w->phys_cursor.y = glyph_row->y;
 33734           w->phys_cursor.hpos = hpos;
 33735           w->phys_cursor.vpos = vpos;
 33736         }
 33737       return;
 33738     }
 33739 
 33740   glyph = NULL;
 33741   if (0 <= hpos && hpos < glyph_row->used[TEXT_AREA])
 33742     glyph = glyph_row->glyphs[TEXT_AREA] + hpos;
 33743 
 33744   eassert (input_blocked_p ());
 33745 
 33746   /* Set new_cursor_type to the cursor we want to be displayed.  */
 33747   new_cursor_type = get_window_cursor_type (w, glyph,
 33748                                             &new_cursor_width, &active_cursor);
 33749 
 33750   /* If cursor is currently being shown and we don't want it to be or
 33751      it is in the wrong place, or the cursor type is not what we want,
 33752      erase it.  */
 33753   if (w->phys_cursor_on_p
 33754       && (!on
 33755           || w->phys_cursor.x != x
 33756           || w->phys_cursor.y != y
 33757           /* HPOS can be negative in R2L rows whose
 33758              exact_window_width_line_p flag is set (i.e. their newline
 33759              would "overflow into the fringe").  */
 33760           || hpos < 0
 33761           || new_cursor_type != w->phys_cursor_type
 33762           || ((new_cursor_type == BAR_CURSOR || new_cursor_type == HBAR_CURSOR)
 33763               && new_cursor_width != w->phys_cursor_width)))
 33764     erase_phys_cursor (w);
 33765 
 33766   /* Don't check phys_cursor_on_p here because that flag is only set
 33767      to false in some cases where we know that the cursor has been
 33768      completely erased, to avoid the extra work of erasing the cursor
 33769      twice.  In other words, phys_cursor_on_p can be true and the cursor
 33770      still not be visible, or it has only been partly erased.  */
 33771   if (on)
 33772     {
 33773       w->phys_cursor_ascent = glyph_row->ascent;
 33774       w->phys_cursor_height = glyph_row->height;
 33775 
 33776       /* Set phys_cursor_.* before x_draw_.* is called because some
 33777          of them may need the information.  */
 33778       w->phys_cursor.x = x;
 33779       w->phys_cursor.y = glyph_row->y;
 33780       w->phys_cursor.hpos = hpos;
 33781       w->phys_cursor.vpos = vpos;
 33782     }
 33783 
 33784   FRAME_RIF (f)->draw_window_cursor (w, glyph_row, x, y,
 33785                                      new_cursor_type, new_cursor_width,
 33786                                      on, active_cursor);
 33787 }
 33788 
 33789 
 33790 /* Switch the display of W's cursor on or off, according to the value
 33791    of ON.  */
 33792 
 33793 static void
 33794 update_window_cursor (struct window *w, bool on)
 33795 {
 33796   /* Don't update cursor in windows whose frame is in the process
 33797      of being deleted.  */
 33798   if (w->current_matrix)
 33799     {
 33800       int hpos = w->phys_cursor.hpos;
 33801       int vpos = w->phys_cursor.vpos;
 33802       struct glyph_row *row;
 33803 
 33804       if (vpos >= w->current_matrix->nrows
 33805           || hpos >= w->current_matrix->matrix_w)
 33806         return;
 33807 
 33808       row = MATRIX_ROW (w->current_matrix, vpos);
 33809 
 33810       /* When the window is hscrolled, cursor hpos can legitimately be
 33811          out of bounds, but we draw the cursor at the corresponding
 33812          window margin in that case.  */
 33813       if (!row->reversed_p && hpos < 0)
 33814         hpos = 0;
 33815       if (row->reversed_p && hpos >= row->used[TEXT_AREA])
 33816         hpos = row->used[TEXT_AREA] - 1;
 33817 
 33818       block_input ();
 33819       display_and_set_cursor (w, on, hpos, vpos,
 33820                               w->phys_cursor.x, w->phys_cursor.y);
 33821       unblock_input ();
 33822     }
 33823 }
 33824 
 33825 
 33826 /* Call update_window_cursor with parameter ON_P on all leaf windows
 33827    in the window tree rooted at W.  */
 33828 
 33829 static void
 33830 update_cursor_in_window_tree (struct window *w, bool on_p)
 33831 {
 33832   while (w)
 33833     {
 33834       if (WINDOWP (w->contents))
 33835         update_cursor_in_window_tree (XWINDOW (w->contents), on_p);
 33836       else
 33837         update_window_cursor (w, on_p);
 33838 
 33839       w = NILP (w->next) ? 0 : XWINDOW (w->next);
 33840     }
 33841 }
 33842 
 33843 
 33844 /* EXPORT:
 33845    Display the cursor on window W, or clear it, according to ON_P.
 33846    Don't change the cursor's position.  */
 33847 
 33848 void
 33849 gui_update_cursor (struct frame *f, bool on_p)
 33850 {
 33851   update_cursor_in_window_tree (XWINDOW (f->root_window), on_p);
 33852 }
 33853 
 33854 
 33855 /* EXPORT:
 33856    Clear the cursor of window W to background color, and mark the
 33857    cursor as not shown.  This is used when the text where the cursor
 33858    is about to be rewritten.  */
 33859 
 33860 void
 33861 gui_clear_cursor (struct window *w)
 33862 {
 33863   if (FRAME_REDISPLAY_P (XFRAME (w->frame)) && w->phys_cursor_on_p)
 33864     update_window_cursor (w, false);
 33865 }
 33866 
 33867 #endif /* HAVE_WINDOW_SYSTEM */
 33868 
 33869 /* Implementation of draw_row_with_mouse_face for GUI sessions, GPM,
 33870    and MSDOS.  */
 33871 static void
 33872 draw_row_with_mouse_face (struct window *w, int start_x, struct glyph_row *row,
 33873                           int start_hpos, int end_hpos,
 33874                           enum draw_glyphs_face draw)
 33875 {
 33876 #ifdef HAVE_WINDOW_SYSTEM
 33877   if (FRAME_WINDOW_P (XFRAME (w->frame)))
 33878     {
 33879       draw_glyphs (w, start_x, row, TEXT_AREA, start_hpos, end_hpos, draw, 0);
 33880       return;
 33881     }
 33882 #endif
 33883 
 33884 #ifndef HAVE_ANDROID
 33885   tty_draw_row_with_mouse_face (w, row, start_hpos, end_hpos, draw);
 33886 #endif
 33887 }
 33888 
 33889 /* Display the active region described by mouse_face_* according to DRAW.  */
 33890 
 33891 static void
 33892 show_mouse_face (Mouse_HLInfo *hlinfo, enum draw_glyphs_face draw)
 33893 {
 33894   /* Don't bother doing anything if the mouse-face window is not set
 33895      up.  */
 33896   if (!WINDOWP (hlinfo->mouse_face_window))
 33897     return;
 33898 
 33899   struct window *w = XWINDOW (hlinfo->mouse_face_window);
 33900   struct frame *f = XFRAME (WINDOW_FRAME (w));
 33901 
 33902   /* Don't bother doing anything if we are on a wrong frame.  */
 33903   if (f != hlinfo->mouse_face_mouse_frame)
 33904     return;
 33905 
 33906   if (/* If window is in the process of being destroyed, don't bother
 33907          to do anything.  */
 33908       w->current_matrix != NULL
 33909       /* Don't update mouse highlight if hidden.  */
 33910       && (draw != DRAW_MOUSE_FACE || !hlinfo->mouse_face_hidden)
 33911       /* Recognize when we are called to operate on rows that don't exist
 33912          anymore.  This can happen when a window is split.  */
 33913       && hlinfo->mouse_face_end_row < w->current_matrix->nrows)
 33914     {
 33915       bool phys_cursor_on_p = w->phys_cursor_on_p;
 33916 #ifdef HAVE_WINDOW_SYSTEM
 33917       int mouse_off = 0;
 33918 #endif
 33919       struct glyph_row *row, *first, *last;
 33920 
 33921       first = MATRIX_ROW (w->current_matrix, hlinfo->mouse_face_beg_row);
 33922       last = MATRIX_ROW (w->current_matrix, hlinfo->mouse_face_end_row);
 33923 
 33924       for (row = first; row <= last && row->enabled_p; ++row)
 33925         {
 33926           int start_hpos, end_hpos, start_x;
 33927 
 33928           /* For all but the first row, the highlight starts at column 0.  */
 33929           if (row == first)
 33930             {
 33931               /* R2L rows have BEG and END in reversed order, but the
 33932                  screen drawing geometry is always left to right.  So
 33933                  we need to mirror the beginning and end of the
 33934                  highlighted area in R2L rows.  */
 33935               if (!row->reversed_p)
 33936                 {
 33937                   start_hpos = hlinfo->mouse_face_beg_col;
 33938                   start_x = hlinfo->mouse_face_beg_x;
 33939                 }
 33940               else if (row == last)
 33941                 {
 33942                   start_hpos = hlinfo->mouse_face_end_col;
 33943                   start_x = hlinfo->mouse_face_end_x;
 33944                 }
 33945               else
 33946                 {
 33947                   start_hpos = 0;
 33948                   start_x = 0;
 33949                 }
 33950             }
 33951           else if (row->reversed_p && row == last)
 33952             {
 33953               start_hpos = hlinfo->mouse_face_end_col;
 33954               start_x = hlinfo->mouse_face_end_x;
 33955             }
 33956           else
 33957             {
 33958               start_hpos = 0;
 33959               start_x = 0;
 33960             }
 33961 
 33962           if (row == last)
 33963             {
 33964               if (!row->reversed_p)
 33965                 end_hpos = hlinfo->mouse_face_end_col;
 33966               else if (row == first)
 33967                 end_hpos = hlinfo->mouse_face_beg_col;
 33968               else
 33969                 {
 33970                   end_hpos = row->used[TEXT_AREA];
 33971                   if (draw == DRAW_NORMAL_TEXT)
 33972                     row->fill_line_p = true; /* Clear to end of line.  */
 33973                 }
 33974             }
 33975           else if (row->reversed_p && row == first)
 33976             end_hpos = hlinfo->mouse_face_beg_col;
 33977           else
 33978             {
 33979               end_hpos = row->used[TEXT_AREA];
 33980               if (draw == DRAW_NORMAL_TEXT)
 33981                 row->fill_line_p = true; /* Clear to end of line.  */
 33982             }
 33983 
 33984           if (end_hpos > start_hpos)
 33985             {
 33986               draw_row_with_mouse_face (w, start_x, row,
 33987                                         start_hpos, end_hpos, draw);
 33988 
 33989               row->mouse_face_p
 33990                 = draw == DRAW_MOUSE_FACE || draw == DRAW_IMAGE_RAISED;
 33991             }
 33992 #ifdef HAVE_WINDOW_SYSTEM
 33993           /* Compute the cursor offset due to mouse-highlight.  */
 33994           if ((MATRIX_ROW_VPOS (row, w->current_matrix) == w->phys_cursor.vpos)
 33995               /* But not when highlighting a pseudo window, such as
 33996                  the toolbar, which can't have a cursor anyway.  */
 33997               && !w->pseudo_window_p
 33998               && draw == DRAW_MOUSE_FACE)
 33999             get_cursor_offset_for_mouse_face (w, row, &mouse_off);
 34000 #endif
 34001         }
 34002 
 34003       /* When we've written over the cursor, arrange for it to
 34004          be displayed again.  */
 34005       if (FRAME_WINDOW_P (f)
 34006           && phys_cursor_on_p && !w->phys_cursor_on_p)
 34007         {
 34008 #ifdef HAVE_WINDOW_SYSTEM
 34009           int hpos = w->phys_cursor.hpos;
 34010           int old_phys_cursor_x = w->phys_cursor.x;
 34011 
 34012           /* When the window is hscrolled, cursor hpos can legitimately be
 34013              out of bounds, but we draw the cursor at the corresponding
 34014              window margin in that case.  */
 34015           if (!row->reversed_p && hpos < 0)
 34016             hpos = 0;
 34017           if (row->reversed_p && hpos >= row->used[TEXT_AREA])
 34018             hpos = row->used[TEXT_AREA] - 1;
 34019 
 34020           block_input ();
 34021           display_and_set_cursor (w, true, hpos, w->phys_cursor.vpos,
 34022                                   w->phys_cursor.x + mouse_off,
 34023                                   w->phys_cursor.y);
 34024           /* Restore the original cursor coordinates, perhaps modified
 34025              to account for mouse-highlight.  */
 34026           w->phys_cursor.x = old_phys_cursor_x;
 34027           unblock_input ();
 34028 #endif  /* HAVE_WINDOW_SYSTEM */
 34029         }
 34030     }
 34031 
 34032 #ifdef HAVE_WINDOW_SYSTEM
 34033   /* Change the mouse cursor.  */
 34034   if (FRAME_WINDOW_P (f) && NILP (track_mouse))
 34035     {
 34036       if (draw == DRAW_NORMAL_TEXT
 34037 #ifndef HAVE_EXT_TOOL_BAR
 34038           && !EQ (hlinfo->mouse_face_window, f->tool_bar_window)
 34039 #endif
 34040           && !EQ (hlinfo->mouse_face_window, f->tab_bar_window))
 34041         FRAME_RIF (f)->define_frame_cursor (f, FRAME_OUTPUT_DATA (f)->text_cursor);
 34042       else
 34043       if (draw == DRAW_MOUSE_FACE)
 34044         FRAME_RIF (f)->define_frame_cursor (f, FRAME_OUTPUT_DATA (f)->hand_cursor);
 34045       else
 34046         FRAME_RIF (f)->define_frame_cursor (f, FRAME_OUTPUT_DATA (f)->nontext_cursor);
 34047     }
 34048 #endif  /* HAVE_WINDOW_SYSTEM */
 34049 }
 34050 
 34051 /* EXPORT:
 34052    Clear out the mouse-highlighted active region.
 34053    Redraw it un-highlighted first.  Value is true if mouse
 34054    face was actually drawn unhighlighted.  */
 34055 
 34056 bool
 34057 clear_mouse_face (Mouse_HLInfo *hlinfo)
 34058 {
 34059   bool cleared
 34060     = !hlinfo->mouse_face_hidden && !NILP (hlinfo->mouse_face_window);
 34061   if (cleared)
 34062     show_mouse_face (hlinfo, DRAW_NORMAL_TEXT);
 34063   hlinfo->mouse_face_beg_row = hlinfo->mouse_face_beg_col = -1;
 34064   hlinfo->mouse_face_end_row = hlinfo->mouse_face_end_col = -1;
 34065   hlinfo->mouse_face_window = Qnil;
 34066   hlinfo->mouse_face_overlay = Qnil;
 34067   return cleared;
 34068 }
 34069 
 34070 /* Return true if the coordinates HPOS and VPOS on windows W are
 34071    within the mouse face on that window.  */
 34072 static bool
 34073 coords_in_mouse_face_p (struct window *w, int hpos, int vpos)
 34074 {
 34075   Mouse_HLInfo *hlinfo = MOUSE_HL_INFO (XFRAME (w->frame));
 34076 
 34077   /* Quickly resolve the easy cases.  */
 34078   if (!(WINDOWP (hlinfo->mouse_face_window)
 34079         && XWINDOW (hlinfo->mouse_face_window) == w))
 34080     return false;
 34081   if (vpos < hlinfo->mouse_face_beg_row
 34082       || vpos > hlinfo->mouse_face_end_row)
 34083     return false;
 34084   if (vpos > hlinfo->mouse_face_beg_row
 34085       && vpos < hlinfo->mouse_face_end_row)
 34086     return true;
 34087 
 34088   if (!MATRIX_ROW (w->current_matrix, vpos)->reversed_p)
 34089     {
 34090       if (hlinfo->mouse_face_beg_row == hlinfo->mouse_face_end_row)
 34091         {
 34092           if (hlinfo->mouse_face_beg_col <= hpos && hpos < hlinfo->mouse_face_end_col)
 34093             return true;
 34094         }
 34095       else if ((vpos == hlinfo->mouse_face_beg_row
 34096                 && hpos >= hlinfo->mouse_face_beg_col)
 34097                || (vpos == hlinfo->mouse_face_end_row
 34098                    && hpos < hlinfo->mouse_face_end_col))
 34099         return true;
 34100     }
 34101   else
 34102     {
 34103        if (hlinfo->mouse_face_beg_row == hlinfo->mouse_face_end_row)
 34104         {
 34105           if (hlinfo->mouse_face_end_col < hpos && hpos <= hlinfo->mouse_face_beg_col)
 34106             return true;
 34107         }
 34108       else if ((vpos == hlinfo->mouse_face_beg_row
 34109                 && hpos <= hlinfo->mouse_face_beg_col)
 34110                || (vpos == hlinfo->mouse_face_end_row
 34111                    && hpos > hlinfo->mouse_face_end_col))
 34112         return true;
 34113     }
 34114   return false;
 34115 }
 34116 
 34117 
 34118 /* EXPORT:
 34119    True if physical cursor of window W is within mouse face.  */
 34120 
 34121 bool
 34122 cursor_in_mouse_face_p (struct window *w)
 34123 {
 34124   int vpos = w->phys_cursor.vpos;
 34125 
 34126   /* If the cursor is outside the matrix glyph rows, it cannot be
 34127      within the mouse face.  */
 34128   if (!(0 <= vpos && vpos < w->current_matrix->nrows))
 34129     return false;
 34130 
 34131   int hpos = w->phys_cursor.hpos;
 34132   struct glyph_row *row = MATRIX_ROW (w->current_matrix, vpos);
 34133 
 34134   /* When the window is hscrolled, cursor hpos can legitimately be out
 34135      of bounds, but we draw the cursor at the corresponding window
 34136      margin in that case.  */
 34137   if (!row->reversed_p && hpos < 0)
 34138     hpos = 0;
 34139   if (row->reversed_p && hpos >= row->used[TEXT_AREA])
 34140     hpos = row->used[TEXT_AREA] - 1;
 34141 
 34142   return coords_in_mouse_face_p (w, hpos, vpos);
 34143 }
 34144 
 34145 
 34146 
 34147 /* Find the glyph rows START_ROW and END_ROW of window W that display
 34148    characters between buffer positions START_CHARPOS and END_CHARPOS
 34149    (excluding END_CHARPOS).  DISP_STRING is a display string that
 34150    covers these buffer positions.  This is similar to
 34151    row_containing_pos, but is more accurate when bidi reordering makes
 34152    buffer positions change non-linearly with glyph rows.  */
 34153 static void
 34154 rows_from_pos_range (struct window *w,
 34155                      ptrdiff_t start_charpos, ptrdiff_t end_charpos,
 34156                      Lisp_Object disp_string,
 34157                      struct glyph_row **start, struct glyph_row **end)
 34158 {
 34159   struct glyph_row *first = MATRIX_FIRST_TEXT_ROW (w->current_matrix);
 34160   int last_y = window_text_bottom_y (w);
 34161   struct glyph_row *row;
 34162 
 34163   *start = NULL;
 34164   *end = NULL;
 34165 
 34166   while (!first->enabled_p
 34167          && first < MATRIX_BOTTOM_TEXT_ROW (w->current_matrix, w))
 34168     first++;
 34169 
 34170   /* Find the START row.  */
 34171   for (row = first;
 34172        row->enabled_p && MATRIX_ROW_BOTTOM_Y (row) <= last_y;
 34173        row++)
 34174     {
 34175       /* A row can potentially be the START row if the range of the
 34176          characters it displays intersects the range
 34177          [START_CHARPOS..END_CHARPOS).  */
 34178       if (! ((start_charpos < MATRIX_ROW_START_CHARPOS (row)
 34179               && end_charpos < MATRIX_ROW_START_CHARPOS (row))
 34180              /* See the commentary in row_containing_pos, for the
 34181                 explanation of the complicated way to check whether
 34182                 some position is beyond the end of the characters
 34183                 displayed by a row.  */
 34184              || ((start_charpos > MATRIX_ROW_END_CHARPOS (row)
 34185                   || (start_charpos == MATRIX_ROW_END_CHARPOS (row)
 34186                       && !row->ends_at_zv_p
 34187                       && !MATRIX_ROW_ENDS_IN_MIDDLE_OF_CHAR_P (row)))
 34188                  && (end_charpos > MATRIX_ROW_END_CHARPOS (row)
 34189                      || (end_charpos == MATRIX_ROW_END_CHARPOS (row)
 34190                          && !row->ends_at_zv_p
 34191                          && !MATRIX_ROW_ENDS_IN_MIDDLE_OF_CHAR_P (row))))))
 34192         {
 34193           /* Found a candidate row.  Now make sure at least one of the
 34194              glyphs it displays has a charpos from the range
 34195              [START_CHARPOS..END_CHARPOS).
 34196 
 34197              This is not obvious because bidi reordering could make
 34198              buffer positions of a row be 1,2,3,102,101,100, and if we
 34199              want to highlight characters in [50..60), we don't want
 34200              this row, even though [50..60) does intersect [1..103),
 34201              the range of character positions given by the row's start
 34202              and end positions.  */
 34203           struct glyph *g = row->glyphs[TEXT_AREA];
 34204           struct glyph *e = g + row->used[TEXT_AREA];
 34205 
 34206           while (g < e)
 34207             {
 34208               if (((BUFFERP (g->object) || NILP (g->object))
 34209                    && start_charpos <= g->charpos && g->charpos < end_charpos)
 34210                   /* A glyph that comes from DISP_STRING is by
 34211                      definition to be highlighted.  */
 34212                   || EQ (g->object, disp_string))
 34213                 *start = row;
 34214               g++;
 34215             }
 34216           if (*start)
 34217             break;
 34218         }
 34219     }
 34220 
 34221   /* Find the END row.  */
 34222   if (!*start
 34223       /* If the last row is partially visible, start looking for END
 34224          from that row, instead of starting from FIRST.  */
 34225       && !(row->enabled_p
 34226            && row->y < last_y && MATRIX_ROW_BOTTOM_Y (row) > last_y))
 34227     row = first;
 34228   for ( ; row->enabled_p && MATRIX_ROW_BOTTOM_Y (row) <= last_y; row++)
 34229     {
 34230       struct glyph_row *next = row + 1;
 34231       ptrdiff_t next_start = MATRIX_ROW_START_CHARPOS (next);
 34232 
 34233       if (!next->enabled_p
 34234           || next >= MATRIX_BOTTOM_TEXT_ROW (w->current_matrix, w)
 34235           /* The first row >= START whose range of displayed characters
 34236              does NOT intersect the range [START_CHARPOS..END_CHARPOS]
 34237              is the row END + 1.  */
 34238           || (start_charpos < next_start
 34239               && end_charpos < next_start)
 34240           || ((start_charpos > MATRIX_ROW_END_CHARPOS (next)
 34241                || (start_charpos == MATRIX_ROW_END_CHARPOS (next)
 34242                    && !next->ends_at_zv_p
 34243                    && !MATRIX_ROW_ENDS_IN_MIDDLE_OF_CHAR_P (next)))
 34244               && (end_charpos > MATRIX_ROW_END_CHARPOS (next)
 34245                   || (end_charpos == MATRIX_ROW_END_CHARPOS (next)
 34246                       && !next->ends_at_zv_p
 34247                       && !MATRIX_ROW_ENDS_IN_MIDDLE_OF_CHAR_P (next)))))
 34248         {
 34249           *end = row;
 34250           break;
 34251         }
 34252       else
 34253         {
 34254           /* If the next row's edges intersect [START_CHARPOS..END_CHARPOS],
 34255              but none of the characters it displays are in the range, it is
 34256              also END + 1. */
 34257           struct glyph *g = next->glyphs[TEXT_AREA];
 34258           struct glyph *s = g;
 34259           struct glyph *e = g + next->used[TEXT_AREA];
 34260 
 34261           while (g < e)
 34262             {
 34263               if (((BUFFERP (g->object) || NILP (g->object))
 34264                    && ((start_charpos <= g->charpos && g->charpos < end_charpos)
 34265                        /* If the buffer position of the first glyph in
 34266                           the row is equal to END_CHARPOS, it means
 34267                           the last character to be highlighted is the
 34268                           newline of ROW, and we must consider NEXT as
 34269                           END, not END+1.  */
 34270                        || (((!next->reversed_p && g == s)
 34271                             || (next->reversed_p && g == e - 1))
 34272                            && (g->charpos == end_charpos
 34273                                /* Special case for when NEXT is an
 34274                                   empty line at ZV.  */
 34275                                || (g->charpos == -1
 34276                                    && !row->ends_at_zv_p
 34277                                    && next_start == end_charpos)))))
 34278                   /* A glyph that comes from DISP_STRING is by
 34279                      definition to be highlighted.  */
 34280                   || EQ (g->object, disp_string))
 34281                 break;
 34282               g++;
 34283             }
 34284           if (g == e)
 34285             {
 34286               *end = row;
 34287               break;
 34288             }
 34289           /* The first row that ends at ZV must be the last to be
 34290              highlighted.  */
 34291           else if (next->ends_at_zv_p)
 34292             {
 34293               *end = next;
 34294               break;
 34295             }
 34296         }
 34297     }
 34298 }
 34299 
 34300 /* This function sets the mouse_face_* elements of HLINFO, assuming
 34301    the mouse cursor is on a glyph with buffer charpos MOUSE_CHARPOS in
 34302    window WINDOW.  START_CHARPOS and END_CHARPOS are buffer positions
 34303    for the overlay or run of text properties specifying the mouse
 34304    face.  BEFORE_STRING and AFTER_STRING, if non-nil, are a
 34305    before-string and after-string that must also be highlighted.
 34306    DISP_STRING, if non-nil, is a display string that may cover some
 34307    or all of the highlighted text.  */
 34308 
 34309 static void
 34310 mouse_face_from_buffer_pos (Lisp_Object window,
 34311                             Mouse_HLInfo *hlinfo,
 34312                             ptrdiff_t mouse_charpos,
 34313                             ptrdiff_t start_charpos,
 34314                             ptrdiff_t end_charpos,
 34315                             Lisp_Object before_string,
 34316                             Lisp_Object after_string,
 34317                             Lisp_Object disp_string)
 34318 {
 34319   struct window *w = XWINDOW (window);
 34320   struct glyph_row *first = MATRIX_FIRST_TEXT_ROW (w->current_matrix);
 34321   struct glyph_row *r1, *r2;
 34322   struct glyph *glyph, *end;
 34323   ptrdiff_t ignore, pos;
 34324   int x;
 34325 
 34326   eassert (NILP (disp_string) || STRINGP (disp_string));
 34327   eassert (NILP (before_string) || STRINGP (before_string));
 34328   eassert (NILP (after_string) || STRINGP (after_string));
 34329 
 34330   /* Find the rows corresponding to START_CHARPOS and END_CHARPOS.  */
 34331   rows_from_pos_range (w, start_charpos, end_charpos, disp_string, &r1, &r2);
 34332   if (r1 == NULL)
 34333     r1 = MATRIX_ROW (w->current_matrix, w->window_end_vpos);
 34334   /* If the before-string or display-string contains newlines,
 34335      rows_from_pos_range skips to its last row.  Move back.  */
 34336   if (!NILP (before_string) || !NILP (disp_string))
 34337     {
 34338       struct glyph_row *prev;
 34339       while ((prev = r1 - 1, prev >= first)
 34340              && MATRIX_ROW_END_CHARPOS (prev) == start_charpos
 34341              && prev->used[TEXT_AREA] > 0)
 34342         {
 34343           struct glyph *beg = prev->glyphs[TEXT_AREA];
 34344           glyph = beg + prev->used[TEXT_AREA];
 34345           while (--glyph >= beg && NILP (glyph->object));
 34346           if (glyph < beg
 34347               || !(EQ (glyph->object, before_string)
 34348                    || EQ (glyph->object, disp_string)))
 34349             break;
 34350           r1 = prev;
 34351         }
 34352     }
 34353   if (r2 == NULL)
 34354     {
 34355       r2 = MATRIX_ROW (w->current_matrix, w->window_end_vpos);
 34356       hlinfo->mouse_face_past_end = true;
 34357     }
 34358   else if (!NILP (after_string))
 34359     {
 34360       /* If the after-string has newlines, advance to its last row.  */
 34361       struct glyph_row *next;
 34362       struct glyph_row *last
 34363         = MATRIX_ROW (w->current_matrix, w->window_end_vpos);
 34364 
 34365       for (next = r2 + 1;
 34366            next <= last
 34367              && next->used[TEXT_AREA] > 0
 34368              && EQ (next->glyphs[TEXT_AREA]->object, after_string);
 34369            ++next)
 34370         r2 = next;
 34371     }
 34372   /* The rest of the display engine assumes that mouse_face_beg_row is
 34373      either above mouse_face_end_row or identical to it.  But with
 34374      bidi-reordered continued lines, the row for START_CHARPOS could
 34375      be below the row for END_CHARPOS.  If so, swap the rows and store
 34376      them in correct order.  */
 34377   if (r1->y > r2->y)
 34378     {
 34379       struct glyph_row *tem = r2;
 34380 
 34381       r2 = r1;
 34382       r1 = tem;
 34383     }
 34384 
 34385   hlinfo->mouse_face_beg_row = MATRIX_ROW_VPOS (r1, w->current_matrix);
 34386   hlinfo->mouse_face_end_row = MATRIX_ROW_VPOS (r2, w->current_matrix);
 34387 
 34388   /* For a bidi-reordered row, the positions of BEFORE_STRING,
 34389      AFTER_STRING, DISP_STRING, START_CHARPOS, and END_CHARPOS
 34390      could be anywhere in the row and in any order.  The strategy
 34391      below is to find the leftmost and the rightmost glyph that
 34392      belongs to either of these 3 strings, or whose position is
 34393      between START_CHARPOS and END_CHARPOS, and highlight all the
 34394      glyphs between those two.  This may cover more than just the text
 34395      between START_CHARPOS and END_CHARPOS if the range of characters
 34396      strides the bidi level boundary, e.g. if the beginning is in R2L
 34397      text while the end is in L2R text or vice versa.  */
 34398   if (!r1->reversed_p)
 34399     {
 34400       /* This row is in a left to right paragraph.  Scan it left to
 34401          right.  */
 34402       glyph = r1->glyphs[TEXT_AREA];
 34403       end = glyph + r1->used[TEXT_AREA];
 34404       x = r1->x;
 34405 
 34406       /* Skip truncation glyphs at the start of the glyph row.  */
 34407       if (MATRIX_ROW_DISPLAYS_TEXT_P (r1))
 34408         for (; glyph < end
 34409                && NILP (glyph->object)
 34410                && glyph->charpos < 0;
 34411              ++glyph)
 34412           x += glyph->pixel_width;
 34413 
 34414       /* Scan the glyph row, looking for BEFORE_STRING, AFTER_STRING,
 34415          or DISP_STRING, and the first glyph from buffer whose
 34416          position is between START_CHARPOS and END_CHARPOS.  */
 34417       for (; glyph < end
 34418              && !NILP (glyph->object)
 34419              && !EQ (glyph->object, disp_string)
 34420              && !(BUFFERP (glyph->object)
 34421                   && (glyph->charpos >= start_charpos
 34422                       && glyph->charpos < end_charpos));
 34423            ++glyph)
 34424         {
 34425           /* BEFORE_STRING or AFTER_STRING are only relevant if they
 34426              are present at buffer positions between START_CHARPOS and
 34427              END_CHARPOS, or if they come from an overlay.  */
 34428           if (EQ (glyph->object, before_string))
 34429             {
 34430               pos = string_buffer_position (before_string,
 34431                                             start_charpos);
 34432               /* If pos == 0, it means before_string came from an
 34433                  overlay, not from a buffer position.  */
 34434               if (!pos || (pos >= start_charpos && pos < end_charpos))
 34435                 break;
 34436             }
 34437           else if (EQ (glyph->object, after_string))
 34438             {
 34439               pos = string_buffer_position (after_string, end_charpos);
 34440               if (!pos || (pos >= start_charpos && pos < end_charpos))
 34441                 break;
 34442             }
 34443           x += glyph->pixel_width;
 34444         }
 34445       hlinfo->mouse_face_beg_x = x;
 34446       hlinfo->mouse_face_beg_col = glyph - r1->glyphs[TEXT_AREA];
 34447     }
 34448   else
 34449     {
 34450       /* This row is in a right to left paragraph.  Scan it right to
 34451          left.  */
 34452       struct glyph *g;
 34453 
 34454       end = r1->glyphs[TEXT_AREA] - 1;
 34455       glyph = end + r1->used[TEXT_AREA];
 34456 
 34457       /* Skip truncation glyphs at the start of the glyph row.  */
 34458       if (MATRIX_ROW_DISPLAYS_TEXT_P (r1))
 34459         for (; glyph > end
 34460                && NILP (glyph->object)
 34461                && glyph->charpos < 0;
 34462              --glyph)
 34463           ;
 34464 
 34465       /* Scan the glyph row, looking for BEFORE_STRING, AFTER_STRING,
 34466          or DISP_STRING, and the first glyph from buffer whose
 34467          position is between START_CHARPOS and END_CHARPOS.  */
 34468       for (; glyph > end
 34469              && !NILP (glyph->object)
 34470              && !EQ (glyph->object, disp_string)
 34471              && !(BUFFERP (glyph->object)
 34472                   && (glyph->charpos >= start_charpos
 34473                       && glyph->charpos < end_charpos));
 34474            --glyph)
 34475         {
 34476           /* BEFORE_STRING or AFTER_STRING are only relevant if they
 34477              are present at buffer positions between START_CHARPOS and
 34478              END_CHARPOS, or if they come from an overlay.  */
 34479           if (EQ (glyph->object, before_string))
 34480             {
 34481               pos = string_buffer_position (before_string, start_charpos);
 34482               /* If pos == 0, it means before_string came from an
 34483                  overlay, not from a buffer position.  */
 34484               if (!pos || (pos >= start_charpos && pos < end_charpos))
 34485                 break;
 34486             }
 34487           else if (EQ (glyph->object, after_string))
 34488             {
 34489               pos = string_buffer_position (after_string, end_charpos);
 34490               if (!pos || (pos >= start_charpos && pos < end_charpos))
 34491                 break;
 34492             }
 34493         }
 34494 
 34495       glyph++; /* first glyph to the right of the highlighted area */
 34496       for (g = r1->glyphs[TEXT_AREA], x = r1->x; g < glyph; g++)
 34497         x += g->pixel_width;
 34498       hlinfo->mouse_face_beg_x = x;
 34499       hlinfo->mouse_face_beg_col = glyph - r1->glyphs[TEXT_AREA];
 34500     }
 34501 
 34502   /* If the highlight ends in a different row, compute GLYPH and END
 34503      for the end row.  Otherwise, reuse the values computed above for
 34504      the row where the highlight begins.  */
 34505   if (r2 != r1)
 34506     {
 34507       if (!r2->reversed_p)
 34508         {
 34509           glyph = r2->glyphs[TEXT_AREA];
 34510           end = glyph + r2->used[TEXT_AREA];
 34511           x = r2->x;
 34512         }
 34513       else
 34514         {
 34515           end = r2->glyphs[TEXT_AREA] - 1;
 34516           glyph = end + r2->used[TEXT_AREA];
 34517         }
 34518     }
 34519 
 34520   if (!r2->reversed_p)
 34521     {
 34522       /* Skip truncation and continuation glyphs near the end of the
 34523          row, and also blanks and stretch glyphs inserted by
 34524          extend_face_to_end_of_line.  */
 34525       while (end > glyph
 34526              && NILP ((end - 1)->object))
 34527         --end;
 34528       /* Scan the rest of the glyph row from the end, looking for the
 34529          first glyph that comes from BEFORE_STRING, AFTER_STRING, or
 34530          DISP_STRING, or whose position is between START_CHARPOS
 34531          and END_CHARPOS */
 34532       for (--end;
 34533              end > glyph
 34534              && !NILP (end->object)
 34535              && !EQ (end->object, disp_string)
 34536              && !(BUFFERP (end->object)
 34537                   && (end->charpos >= start_charpos
 34538                       && end->charpos < end_charpos));
 34539            --end)
 34540         {
 34541           /* BEFORE_STRING or AFTER_STRING are only relevant if they
 34542              are present at buffer positions between START_CHARPOS and
 34543              END_CHARPOS, or if they come from an overlay.  */
 34544           if (EQ (end->object, before_string))
 34545             {
 34546               pos = string_buffer_position (before_string, start_charpos);
 34547               if (!pos || (pos >= start_charpos && pos < end_charpos))
 34548                 break;
 34549             }
 34550           else if (EQ (end->object, after_string))
 34551             {
 34552               pos = string_buffer_position (after_string, end_charpos);
 34553               if (!pos || (pos >= start_charpos && pos < end_charpos))
 34554                 break;
 34555             }
 34556         }
 34557       /* Find the X coordinate of the last glyph to be highlighted.  */
 34558       for (; glyph <= end; ++glyph)
 34559         x += glyph->pixel_width;
 34560 
 34561       hlinfo->mouse_face_end_x = x;
 34562       hlinfo->mouse_face_end_col = glyph - r2->glyphs[TEXT_AREA];
 34563     }
 34564   else
 34565     {
 34566       /* Skip truncation and continuation glyphs near the end of the
 34567          row, and also blanks and stretch glyphs inserted by
 34568          extend_face_to_end_of_line.  */
 34569       x = r2->x;
 34570       end++;
 34571       while (end < glyph
 34572              && NILP (end->object))
 34573         {
 34574           x += end->pixel_width;
 34575           ++end;
 34576         }
 34577       /* Scan the rest of the glyph row from the end, looking for the
 34578          first glyph that comes from BEFORE_STRING, AFTER_STRING, or
 34579          DISP_STRING, or whose position is between START_CHARPOS
 34580          and END_CHARPOS */
 34581       for ( ;
 34582              end < glyph
 34583              && !NILP (end->object)
 34584              && !EQ (end->object, disp_string)
 34585              && !(BUFFERP (end->object)
 34586                   && (end->charpos >= start_charpos
 34587                       && end->charpos < end_charpos));
 34588            ++end)
 34589         {
 34590           /* BEFORE_STRING or AFTER_STRING are only relevant if they
 34591              are present at buffer positions between START_CHARPOS and
 34592              END_CHARPOS, or if they come from an overlay.  */
 34593           if (EQ (end->object, before_string))
 34594             {
 34595               pos = string_buffer_position (before_string, start_charpos);
 34596               if (!pos || (pos >= start_charpos && pos < end_charpos))
 34597                 break;
 34598             }
 34599           else if (EQ (end->object, after_string))
 34600             {
 34601               pos = string_buffer_position (after_string, end_charpos);
 34602               if (!pos || (pos >= start_charpos && pos < end_charpos))
 34603                 break;
 34604             }
 34605           x += end->pixel_width;
 34606         }
 34607       /* If we exited the above loop because we arrived at the last
 34608          glyph of the row, and its buffer position is still not in
 34609          range, it means the last character in range is the preceding
 34610          newline.  Bump the end column and x values to get past the
 34611          last glyph.  */
 34612       if (end == glyph
 34613           && BUFFERP (end->object)
 34614           && (end->charpos < start_charpos
 34615               || end->charpos >= end_charpos))
 34616         {
 34617           x += end->pixel_width;
 34618           ++end;
 34619         }
 34620       hlinfo->mouse_face_end_x = x;
 34621       hlinfo->mouse_face_end_col = end - r2->glyphs[TEXT_AREA];
 34622     }
 34623 
 34624   hlinfo->mouse_face_window = window;
 34625   hlinfo->mouse_face_face_id
 34626     = face_at_buffer_position (w, mouse_charpos, &ignore,
 34627                                mouse_charpos + 1,
 34628                                !hlinfo->mouse_face_hidden, -1, 0);
 34629   show_mouse_face (hlinfo, DRAW_MOUSE_FACE);
 34630 }
 34631 
 34632 /* The following function is not used anymore (replaced with
 34633    mouse_face_from_string_pos), but I leave it here for the time
 34634    being, in case someone would.  */
 34635 
 34636 #if false       /* not used */
 34637 
 34638 /* Find the position of the glyph for position POS in OBJECT in
 34639    window W's current matrix, and return in *X, *Y the pixel
 34640    coordinates, and return in *HPOS, *VPOS the column/row of the glyph.
 34641 
 34642    RIGHT_P means return the position of the right edge of the glyph.
 34643    !RIGHT_P means return the left edge position.
 34644 
 34645    If no glyph for POS exists in the matrix, return the position of
 34646    the glyph with the next smaller position that is in the matrix, if
 34647    RIGHT_P is false.  If RIGHT_P, and no glyph for POS
 34648    exists in the matrix, return the position of the glyph with the
 34649    next larger position in OBJECT.
 34650 
 34651    Value is true if a glyph was found.  */
 34652 
 34653 static bool
 34654 fast_find_string_pos (struct window *w, ptrdiff_t pos, Lisp_Object object,
 34655                       int *hpos, int *vpos, int *x, int *y, bool right_p)
 34656 {
 34657   int yb = window_text_bottom_y (w);
 34658   struct glyph_row *r;
 34659   struct glyph *best_glyph = NULL;
 34660   struct glyph_row *best_row = NULL;
 34661   int best_x = 0;
 34662 
 34663   for (r = MATRIX_FIRST_TEXT_ROW (w->current_matrix);
 34664        r->enabled_p && r->y < yb;
 34665        ++r)
 34666     {
 34667       struct glyph *g = r->glyphs[TEXT_AREA];
 34668       struct glyph *e = g + r->used[TEXT_AREA];
 34669       int gx;
 34670 
 34671       for (gx = r->x; g < e; gx += g->pixel_width, ++g)
 34672         if (EQ (g->object, object))
 34673           {
 34674             if (g->charpos == pos)
 34675               {
 34676                 best_glyph = g;
 34677                 best_x = gx;
 34678                 best_row = r;
 34679                 goto found;
 34680               }
 34681             else if (best_glyph == NULL
 34682                      || ((eabs (g->charpos - pos)
 34683                          < eabs (best_glyph->charpos - pos))
 34684                          && (right_p
 34685                              ? g->charpos < pos
 34686                              : g->charpos > pos)))
 34687               {
 34688                 best_glyph = g;
 34689                 best_x = gx;
 34690                 best_row = r;
 34691               }
 34692           }
 34693     }
 34694 
 34695  found:
 34696 
 34697   if (best_glyph)
 34698     {
 34699       *x = best_x;
 34700       *hpos = best_glyph - best_row->glyphs[TEXT_AREA];
 34701 
 34702       if (right_p)
 34703         {
 34704           *x += best_glyph->pixel_width;
 34705           ++*hpos;
 34706         }
 34707 
 34708       *y = best_row->y;
 34709       *vpos = MATRIX_ROW_VPOS (best_row, w->current_matrix);
 34710     }
 34711 
 34712   return best_glyph != NULL;
 34713 }
 34714 #endif  /* not used */
 34715 
 34716 /* Find the positions of the first and the last glyphs in window W's
 34717    current matrix that occlude positions [STARTPOS..ENDPOS) in OBJECT
 34718    (assumed to be a string), and return in HLINFO's mouse_face_*
 34719    members the pixel and column/row coordinates of those glyphs.  */
 34720 
 34721 static void
 34722 mouse_face_from_string_pos (struct window *w, Mouse_HLInfo *hlinfo,
 34723                             Lisp_Object object,
 34724                             ptrdiff_t startpos, ptrdiff_t endpos)
 34725 {
 34726   int yb = window_text_bottom_y (w);
 34727   struct glyph_row *r;
 34728   struct glyph *g, *e;
 34729   int gx;
 34730   bool found = false;
 34731 
 34732   /* Find the glyph row with at least one position in the range
 34733      [STARTPOS..ENDPOS), and the first glyph in that row whose
 34734      position belongs to that range.  */
 34735   for (r = MATRIX_FIRST_TEXT_ROW (w->current_matrix);
 34736        r->enabled_p && r->y < yb;
 34737        ++r)
 34738     {
 34739       if (!r->reversed_p)
 34740         {
 34741           g = r->glyphs[TEXT_AREA];
 34742           e = g + r->used[TEXT_AREA];
 34743           for (gx = r->x; g < e; gx += g->pixel_width, ++g)
 34744             if (EQ (g->object, object)
 34745                 && startpos <= g->charpos && g->charpos < endpos)
 34746               {
 34747                 hlinfo->mouse_face_beg_row
 34748                   = MATRIX_ROW_VPOS (r, w->current_matrix);
 34749                 hlinfo->mouse_face_beg_col = g - r->glyphs[TEXT_AREA];
 34750                 hlinfo->mouse_face_beg_x = gx;
 34751                 found = true;
 34752                 break;
 34753               }
 34754         }
 34755       else
 34756         {
 34757           struct glyph *g1;
 34758 
 34759           e = r->glyphs[TEXT_AREA];
 34760           g = e + r->used[TEXT_AREA];
 34761           for ( ; g > e; --g)
 34762             if (EQ ((g-1)->object, object)
 34763                 && startpos <= (g-1)->charpos && (g-1)->charpos < endpos)
 34764               {
 34765                 hlinfo->mouse_face_beg_row
 34766                   = MATRIX_ROW_VPOS (r, w->current_matrix);
 34767                 hlinfo->mouse_face_beg_col = g - r->glyphs[TEXT_AREA];
 34768                 for (gx = r->x, g1 = r->glyphs[TEXT_AREA]; g1 < g; ++g1)
 34769                   gx += g1->pixel_width;
 34770                 hlinfo->mouse_face_beg_x = gx;
 34771                 found = true;
 34772                 break;
 34773               }
 34774         }
 34775       if (found)
 34776         break;
 34777     }
 34778 
 34779   if (!found)
 34780     return;
 34781 
 34782   /* Starting with the next row, look for the first row which does NOT
 34783      include any glyphs whose positions are in the range.  */
 34784   for (++r; r->enabled_p && r->y < yb; ++r)
 34785     {
 34786       g = r->glyphs[TEXT_AREA];
 34787       e = g + r->used[TEXT_AREA];
 34788       found = false;
 34789       for ( ; g < e; ++g)
 34790         if (EQ (g->object, object)
 34791             && startpos <= g->charpos && g->charpos < endpos)
 34792           {
 34793             found = true;
 34794             break;
 34795           }
 34796       if (!found)
 34797         break;
 34798     }
 34799 
 34800   /* The highlighted region ends on the previous row.  */
 34801   r--;
 34802 
 34803   /* Set the end row.  */
 34804   hlinfo->mouse_face_end_row = MATRIX_ROW_VPOS (r, w->current_matrix);
 34805 
 34806   /* Compute and set the end column and the end column's horizontal
 34807      pixel coordinate.  */
 34808   if (!r->reversed_p)
 34809     {
 34810       g = r->glyphs[TEXT_AREA];
 34811       e = g + r->used[TEXT_AREA];
 34812       for ( ; e > g; --e)
 34813         if (EQ ((e-1)->object, object)
 34814             && startpos <= (e-1)->charpos && (e-1)->charpos < endpos)
 34815           break;
 34816       hlinfo->mouse_face_end_col = e - g;
 34817 
 34818       for (gx = r->x; g < e; ++g)
 34819         gx += g->pixel_width;
 34820       hlinfo->mouse_face_end_x = gx;
 34821     }
 34822   else
 34823     {
 34824       e = r->glyphs[TEXT_AREA];
 34825       g = e + r->used[TEXT_AREA];
 34826       for (gx = r->x ; e < g; ++e)
 34827         {
 34828           if (EQ (e->object, object)
 34829               && startpos <= e->charpos && e->charpos < endpos)
 34830             break;
 34831           gx += e->pixel_width;
 34832         }
 34833       hlinfo->mouse_face_end_col = e - r->glyphs[TEXT_AREA];
 34834       hlinfo->mouse_face_end_x = gx;
 34835     }
 34836 }
 34837 
 34838 #ifdef HAVE_WINDOW_SYSTEM
 34839 
 34840 /* See if position X, Y is within a hot-spot of an image.  */
 34841 
 34842 static bool
 34843 on_hot_spot_p (Lisp_Object hot_spot, int x, int y)
 34844 {
 34845   if (!CONSP (hot_spot))
 34846     return false;
 34847 
 34848   if (EQ (XCAR (hot_spot), Qrect))
 34849     {
 34850       /* CDR is (Top-Left . Bottom-Right) = ((x0 . y0) . (x1 . y1))  */
 34851       Lisp_Object rect = XCDR (hot_spot);
 34852       Lisp_Object tem;
 34853       if (!CONSP (rect))
 34854         return false;
 34855       if (!CONSP (XCAR (rect)))
 34856         return false;
 34857       if (!CONSP (XCDR (rect)))
 34858         return false;
 34859       if (!(tem = XCAR (XCAR (rect)), FIXNUMP (tem) && x >= XFIXNUM (tem)))
 34860         return false;
 34861       if (!(tem = XCDR (XCAR (rect)), FIXNUMP (tem) && y >= XFIXNUM (tem)))
 34862         return false;
 34863       if (!(tem = XCAR (XCDR (rect)), FIXNUMP (tem) && x <= XFIXNUM (tem)))
 34864         return false;
 34865       if (!(tem = XCDR (XCDR (rect)), FIXNUMP (tem) && y <= XFIXNUM (tem)))
 34866         return false;
 34867       return true;
 34868     }
 34869   else if (EQ (XCAR (hot_spot), Qcircle))
 34870     {
 34871       /* CDR is (Center . Radius) = ((x0 . y0) . r) */
 34872       Lisp_Object circ = XCDR (hot_spot);
 34873       Lisp_Object lr, lx0, ly0;
 34874       if (CONSP (circ)
 34875           && CONSP (XCAR (circ))
 34876           && (lr = XCDR (circ), NUMBERP (lr))
 34877           && (lx0 = XCAR (XCAR (circ)), FIXNUMP (lx0))
 34878           && (ly0 = XCDR (XCAR (circ)), FIXNUMP (ly0)))
 34879         {
 34880           double r = XFLOATINT (lr);
 34881           double dx = XFIXNUM (lx0) - x;
 34882           double dy = XFIXNUM (ly0) - y;
 34883           return (dx * dx + dy * dy <= r * r);
 34884         }
 34885     }
 34886   else if (EQ (XCAR (hot_spot), Qpoly))
 34887     {
 34888       /* CDR is [x0 y0 x1 y1 x2 y2 ...x(n-1) y(n-1)] */
 34889       if (VECTORP (XCDR (hot_spot)))
 34890         {
 34891           struct Lisp_Vector *v = XVECTOR (XCDR (hot_spot));
 34892           Lisp_Object *poly = v->contents;
 34893           ptrdiff_t n = v->header.size;
 34894           ptrdiff_t i;
 34895           bool inside = false;
 34896           Lisp_Object lx, ly;
 34897           int x0, y0;
 34898 
 34899           /* Need an even number of coordinates, and at least 3 edges.  */
 34900           if (n < 6 || n & 1)
 34901             return false;
 34902 
 34903           /* Count edge segments intersecting line from (X,Y) to (X,infinity).
 34904              If count is odd, we are inside polygon.  Pixels on edges
 34905              may or may not be included depending on actual geometry of the
 34906              polygon.  */
 34907           if ((lx = poly[n-2], !FIXNUMP (lx))
 34908               || (ly = poly[n-1], !FIXNUMP (lx)))
 34909             return false;
 34910           x0 = XFIXNUM (lx), y0 = XFIXNUM (ly);
 34911           for (i = 0; i < n; i += 2)
 34912             {
 34913               int x1 = x0, y1 = y0;
 34914               if ((lx = poly[i], !FIXNUMP (lx))
 34915                   || (ly = poly[i+1], !FIXNUMP (ly)))
 34916                 return false;
 34917               x0 = XFIXNUM (lx), y0 = XFIXNUM (ly);
 34918 
 34919               /* Does this segment cross the X line?  */
 34920               if (x0 >= x)
 34921                 {
 34922                   if (x1 >= x)
 34923                     continue;
 34924                 }
 34925               else if (x1 < x)
 34926                 continue;
 34927               if (y > y0 && y > y1)
 34928                 continue;
 34929               if (y < y0 + ((y1 - y0) * (x - x0)) / (x1 - x0))
 34930                 inside = !inside;
 34931             }
 34932           return inside;
 34933         }
 34934     }
 34935   return false;
 34936 }
 34937 
 34938 Lisp_Object
 34939 find_hot_spot (Lisp_Object map, int x, int y)
 34940 {
 34941   while (CONSP (map))
 34942     {
 34943       if (CONSP (XCAR (map))
 34944           && on_hot_spot_p (XCAR (XCAR (map)), x, y))
 34945         return XCAR (map);
 34946       map = XCDR (map);
 34947     }
 34948 
 34949   return Qnil;
 34950 }
 34951 
 34952 DEFUN ("lookup-image-map", Flookup_image_map, Slookup_image_map,
 34953        3, 3, 0,
 34954        doc: /* Lookup in image map MAP coordinates X and Y.
 34955 An image map is an alist where each element has the format (AREA ID PLIST).
 34956 An AREA is specified as either a rectangle, a circle, or a polygon:
 34957 A rectangle is a cons (rect . ((x0 . y0) . (x1 . y1))) specifying the
 34958 pixel coordinates of the upper left and bottom right corners.
 34959 A circle is a cons (circle . ((x0 . y0) . r)) specifying the center
 34960 and the radius of the circle; r may be a float or integer.
 34961 A polygon is a cons (poly . [x0 y0 x1 y1 ...]) where each pair in the
 34962 vector describes one corner in the polygon.
 34963 Returns the alist element for the first matching AREA in MAP.  */)
 34964   (Lisp_Object map, Lisp_Object x, Lisp_Object y)
 34965 {
 34966   if (NILP (map))
 34967     return Qnil;
 34968 
 34969   CHECK_FIXNUM (x);
 34970   CHECK_FIXNUM (y);
 34971 
 34972   return find_hot_spot (map,
 34973                         clip_to_bounds (INT_MIN, XFIXNUM (x), INT_MAX),
 34974                         clip_to_bounds (INT_MIN, XFIXNUM (y), INT_MAX));
 34975 }
 34976 #endif  /* HAVE_WINDOW_SYSTEM */
 34977 
 34978 
 34979 /* Display frame CURSOR, optionally using shape defined by POINTER.  */
 34980 static void
 34981 define_frame_cursor1 (struct frame *f, Emacs_Cursor cursor, Lisp_Object pointer)
 34982 {
 34983 #ifdef HAVE_WINDOW_SYSTEM
 34984   if (!FRAME_WINDOW_P (f))
 34985     return;
 34986 
 34987   /* Do not change cursor shape while dragging mouse.  */
 34988   if (EQ (track_mouse, Qdragging) || EQ (track_mouse, Qdropping)
 34989       || EQ (track_mouse, Qdrag_source))
 34990     return;
 34991 
 34992   if (!NILP (pointer))
 34993     {
 34994       if (EQ (pointer, Qarrow))
 34995         cursor = FRAME_OUTPUT_DATA (f)->nontext_cursor;
 34996       else if (EQ (pointer, Qhand))
 34997         cursor = FRAME_OUTPUT_DATA (f)->hand_cursor;
 34998       else if (EQ (pointer, Qtext))
 34999         cursor = FRAME_OUTPUT_DATA (f)->text_cursor;
 35000       else if (EQ (pointer, intern ("hdrag")))
 35001         cursor = FRAME_OUTPUT_DATA (f)->horizontal_drag_cursor;
 35002       else if (EQ (pointer, intern ("nhdrag")))
 35003         cursor = FRAME_OUTPUT_DATA (f)->vertical_drag_cursor;
 35004 # ifdef HAVE_X_WINDOWS
 35005       else if (EQ (pointer, intern ("vdrag")))
 35006         cursor = FRAME_DISPLAY_INFO (f)->vertical_scroll_bar_cursor;
 35007 # endif
 35008       else if (EQ (pointer, intern ("hourglass")))
 35009         cursor = FRAME_OUTPUT_DATA (f)->hourglass_cursor;
 35010       else if (EQ (pointer, Qmodeline))
 35011         cursor = FRAME_OUTPUT_DATA (f)->modeline_cursor;
 35012       else
 35013         cursor = FRAME_OUTPUT_DATA (f)->nontext_cursor;
 35014     }
 35015 
 35016   if (cursor != No_Cursor)
 35017     FRAME_RIF (f)->define_frame_cursor (f, cursor);
 35018 #endif
 35019 }
 35020 
 35021 /* Take proper action when mouse has moved to the mode or header line
 35022    or marginal area AREA of window W, x-position X and y-position Y.
 35023    X is relative to the start of the text display area of W, so the
 35024    width of bitmap areas and scroll bars must be subtracted to get a
 35025    position relative to the start of the mode line.  */
 35026 
 35027 static void
 35028 note_mode_line_or_margin_highlight (Lisp_Object window, int x, int y,
 35029                                     enum window_part area)
 35030 {
 35031   struct window *w = XWINDOW (window);
 35032   struct frame *f = XFRAME (w->frame);
 35033   Mouse_HLInfo *hlinfo = MOUSE_HL_INFO (f);
 35034   Emacs_Cursor cursor = No_Cursor;
 35035   Lisp_Object pointer = Qnil;
 35036   int dx, dy, width, height;
 35037   ptrdiff_t charpos;
 35038   Lisp_Object string, object = Qnil;
 35039   Lisp_Object pos UNINIT;
 35040   Lisp_Object mouse_face;
 35041   int original_x_pixel = x;
 35042   struct glyph * glyph = NULL, * row_start_glyph = NULL;
 35043   struct glyph_row *row UNINIT;
 35044 
 35045   if (area == ON_MODE_LINE || area == ON_HEADER_LINE || area == ON_TAB_LINE)
 35046     {
 35047       int x0;
 35048       struct glyph *end;
 35049 
 35050       /* Kludge alert: mode_line_string takes X/Y in pixels, but
 35051          returns them in row/column units!  */
 35052       string = mode_line_string (w, area, &x, &y, &charpos,
 35053                                  &object, &dx, &dy, &width, &height);
 35054 
 35055       row = (area == ON_MODE_LINE
 35056              ? MATRIX_MODE_LINE_ROW (w->current_matrix)
 35057              : (area == ON_TAB_LINE
 35058                 ? MATRIX_TAB_LINE_ROW (w->current_matrix)
 35059                 : MATRIX_HEADER_LINE_ROW (w->current_matrix)));
 35060 
 35061       /* Find the glyph under the mouse pointer.  */
 35062       if (row->mode_line_p && row->enabled_p)
 35063         {
 35064           glyph = row_start_glyph = row->glyphs[TEXT_AREA];
 35065           end = glyph + row->used[TEXT_AREA];
 35066 
 35067           for (x0 = original_x_pixel;
 35068                glyph < end && x0 >= glyph->pixel_width;
 35069                ++glyph)
 35070             x0 -= glyph->pixel_width;
 35071 
 35072           if (glyph >= end)
 35073             glyph = NULL;
 35074         }
 35075     }
 35076   else
 35077     {
 35078       x -= WINDOW_LEFT_SCROLL_BAR_AREA_WIDTH (w);
 35079       /* Kludge alert: marginal_area_string takes X/Y in pixels, but
 35080          returns them in row/column units!  */
 35081       string = marginal_area_string (w, area, &x, &y, &charpos,
 35082                                      &object, &dx, &dy, &width, &height);
 35083     }
 35084 
 35085   Lisp_Object help = Qnil;
 35086 
 35087 #ifdef HAVE_WINDOW_SYSTEM
 35088   if (IMAGEP (object))
 35089     {
 35090       Lisp_Object image_map, hotspot;
 35091       if ((image_map = plist_get (XCDR (object), QCmap),
 35092            !NILP (image_map))
 35093           && (hotspot = find_hot_spot (image_map, dx, dy),
 35094               CONSP (hotspot))
 35095           && (hotspot = XCDR (hotspot), CONSP (hotspot)))
 35096         {
 35097           Lisp_Object plist;
 35098 
 35099           /* Could check XCAR (hotspot) to see if we enter/leave this hot-spot.
 35100              If so, we could look for mouse-enter, mouse-leave
 35101              properties in PLIST (and do something...).  */
 35102           hotspot = XCDR (hotspot);
 35103           if (CONSP (hotspot)
 35104               && (plist = XCAR (hotspot), CONSP (plist)))
 35105             {
 35106               pointer = plist_get (plist, Qpointer);
 35107               if (NILP (pointer))
 35108                 pointer = Qhand;
 35109               help = plist_get (plist, Qhelp_echo);
 35110               if (!NILP (help))
 35111                 {
 35112                   help_echo_string = help;
 35113                   XSETWINDOW (help_echo_window, w);
 35114                   help_echo_object = w->contents;
 35115                   help_echo_pos = charpos;
 35116                 }
 35117             }
 35118         }
 35119       if (NILP (pointer))
 35120         pointer = plist_get (XCDR (object), QCpointer);
 35121     }
 35122 #endif  /* HAVE_WINDOW_SYSTEM */
 35123 
 35124   /* CHARPOS can be beyond the last position of STRING due, e.g., to
 35125      min-width 'display' property.  Fix that, to let all the calls to
 35126      get-text-property below do their thing.  */
 35127   if (STRINGP (string))
 35128     pos = make_fixnum (min (charpos, SCHARS (string) - 1));
 35129 
 35130   /* Set the help text and mouse pointer.  If the mouse is on a part
 35131      of the mode line without any text (e.g. past the right edge of
 35132      the mode line text), use that windows's mode line help echo if it
 35133      has been set.  */
 35134   if (STRINGP (string) || area == ON_MODE_LINE || area == ON_HEADER_LINE
 35135       || area == ON_TAB_LINE)
 35136     {
 35137       /* Arrange to display the help by setting the global variables
 35138          help_echo_string, help_echo_object, and help_echo_pos.  */
 35139       if (NILP (help))
 35140         {
 35141           if (STRINGP (string))
 35142             help = Fget_text_property (pos, Qhelp_echo, string);
 35143 
 35144           if (!NILP (help))
 35145             {
 35146               help_echo_string = help;
 35147               XSETWINDOW (help_echo_window, w);
 35148               help_echo_object = string;
 35149               help_echo_pos = charpos;
 35150             }
 35151           else if (area == ON_MODE_LINE
 35152                    && !NILP (w->mode_line_help_echo))
 35153             {
 35154               help_echo_string =  w->mode_line_help_echo;
 35155               XSETWINDOW (help_echo_window, w);
 35156               help_echo_object = Qnil;
 35157               help_echo_pos = -1;
 35158             }
 35159         }
 35160 
 35161 #ifdef HAVE_WINDOW_SYSTEM
 35162       /* Change the mouse pointer according to what is under it.  */
 35163       if (FRAME_WINDOW_P (f))
 35164         {
 35165           bool draggable = (! WINDOW_BOTTOMMOST_P (w)
 35166                             || minibuf_level
 35167                             || NILP (Vresize_mini_windows));
 35168 
 35169           if (STRINGP (string))
 35170             {
 35171               cursor = FRAME_OUTPUT_DATA (f)->nontext_cursor;
 35172 
 35173               if (NILP (pointer))
 35174                 pointer = Fget_text_property (pos, Qpointer, string);
 35175 
 35176               /* Change the mouse pointer according to what is under X/Y.  */
 35177               if (NILP (pointer)
 35178                   && (area == ON_MODE_LINE || area == ON_HEADER_LINE
 35179                       || area == ON_TAB_LINE))
 35180                 {
 35181                   Lisp_Object map;
 35182 
 35183                   map = Fget_text_property (pos, Qlocal_map, string);
 35184                   if (!KEYMAPP (map))
 35185                     map = Fget_text_property (pos, Qkeymap, string);
 35186                   if (!KEYMAPP (map) && draggable && area == ON_MODE_LINE)
 35187                     cursor = FRAME_OUTPUT_DATA (f)->vertical_drag_cursor;
 35188                 }
 35189             }
 35190           else if (draggable && area == ON_MODE_LINE)
 35191             cursor = FRAME_OUTPUT_DATA (f)->vertical_drag_cursor;
 35192           else if ((area == ON_MODE_LINE
 35193                     && WINDOW_BOTTOMMOST_P (w)
 35194                     && !FRAME_HAS_MINIBUF_P (f)
 35195                     && !NILP (Fframe_parameter
 35196                               (w->frame, Qdrag_with_mode_line)))
 35197                    || (((area == ON_HEADER_LINE
 35198                          && !NILP (Fframe_parameter
 35199                                    (w->frame, Qdrag_with_header_line)))
 35200                         || (area == ON_TAB_LINE
 35201                             && !NILP (Fframe_parameter
 35202                                       (w->frame, Qdrag_with_tab_line))))
 35203                        && WINDOW_TOPMOST_P (w)))
 35204             cursor = FRAME_OUTPUT_DATA (f)->hand_cursor;
 35205           else
 35206             cursor = FRAME_OUTPUT_DATA (f)->nontext_cursor;
 35207         }
 35208 #endif
 35209     }
 35210 
 35211   /* Change the mouse face according to what is under X/Y.  */
 35212   bool mouse_face_shown = false;
 35213 
 35214   if (STRINGP (string))
 35215     {
 35216       mouse_face = Fget_text_property (pos, Qmouse_face, string);
 35217       if (!NILP (Vmouse_highlight) && !NILP (mouse_face)
 35218           && ((area == ON_MODE_LINE) || (area == ON_HEADER_LINE)
 35219               || (area == ON_TAB_LINE))
 35220           && glyph)
 35221         {
 35222           Lisp_Object b, e;
 35223 
 35224           struct glyph * tmp_glyph;
 35225 
 35226           int gpos;
 35227           int gseq_length;
 35228           int total_pixel_width;
 35229           ptrdiff_t begpos, endpos, ignore;
 35230 
 35231           int vpos, hpos;
 35232 
 35233           b = Fprevious_single_property_change (make_fixnum (charpos + 1),
 35234                                                 Qmouse_face, string, Qnil);
 35235           if (NILP (b))
 35236             begpos = 0;
 35237           else
 35238             begpos = XFIXNUM (b);
 35239 
 35240           e = Fnext_single_property_change (pos, Qmouse_face, string, Qnil);
 35241           if (NILP (e))
 35242             endpos = SCHARS (string);
 35243           else
 35244             endpos = XFIXNUM (e);
 35245 
 35246           /* Calculate the glyph position GPOS of GLYPH in the
 35247              displayed string, relative to the beginning of the
 35248              highlighted part of the string.
 35249 
 35250              Note: GPOS is different from CHARPOS.  CHARPOS is the
 35251              position of GLYPH in the internal string object.  A mode
 35252              line string format has structures which are converted to
 35253              a flattened string by the Emacs Lisp interpreter.  The
 35254              internal string is an element of those structures.  The
 35255              displayed string is the flattened string.  */
 35256           tmp_glyph = row_start_glyph;
 35257           while (tmp_glyph < glyph
 35258                  && (!(EQ (tmp_glyph->object, glyph->object)
 35259                        && begpos <= tmp_glyph->charpos
 35260                        && tmp_glyph->charpos < endpos)))
 35261             tmp_glyph++;
 35262           gpos = glyph - tmp_glyph;
 35263 
 35264           /* Calculate the length GSEQ_LENGTH of the glyph sequence of
 35265              the highlighted part of the displayed string to which
 35266              GLYPH belongs.  Note: GSEQ_LENGTH is different from
 35267              SCHARS (STRING), because the latter returns the length of
 35268              the internal string.  */
 35269           for (tmp_glyph = row->glyphs[TEXT_AREA] + row->used[TEXT_AREA] - 1;
 35270                tmp_glyph > glyph
 35271                  && (!(EQ (tmp_glyph->object, glyph->object)
 35272                        && begpos <= tmp_glyph->charpos
 35273                        && tmp_glyph->charpos < endpos));
 35274                tmp_glyph--)
 35275             ;
 35276           gseq_length = gpos + (tmp_glyph - glyph) + 1;
 35277 
 35278           /* Calculate the total pixel width of all the glyphs between
 35279              the beginning of the highlighted area and GLYPH.  */
 35280           total_pixel_width = 0;
 35281           for (tmp_glyph = glyph - gpos; tmp_glyph != glyph; tmp_glyph++)
 35282             total_pixel_width += tmp_glyph->pixel_width;
 35283 
 35284           /* Pre calculation of re-rendering position.  Note: X is in
 35285              column units here, after the call to mode_line_string or
 35286              marginal_area_string.  */
 35287           hpos = x - gpos;
 35288           vpos = (area == ON_MODE_LINE
 35289                   ? (w->current_matrix)->nrows - 1
 35290                   : (area == ON_TAB_LINE
 35291                      ? 0
 35292                      : (w->current_matrix->tab_line_p
 35293                         ? 1
 35294                         : 0)));
 35295 
 35296           /* If GLYPH's position is included in the region that is
 35297              already drawn in mouse face, we have nothing to do.  */
 35298           if ( EQ (window, hlinfo->mouse_face_window)
 35299                && (!row->reversed_p
 35300                    ? (hlinfo->mouse_face_beg_col <= hpos
 35301                       && hpos < hlinfo->mouse_face_end_col)
 35302                    /* In R2L rows we swap BEG and END, see below.  */
 35303                    : (hlinfo->mouse_face_end_col <= hpos
 35304                       && hpos < hlinfo->mouse_face_beg_col))
 35305                && hlinfo->mouse_face_beg_row == vpos )
 35306             return;
 35307 
 35308           if (clear_mouse_face (hlinfo))
 35309             cursor = No_Cursor;
 35310 
 35311           if (!row->reversed_p)
 35312             {
 35313               hlinfo->mouse_face_beg_col = hpos;
 35314               hlinfo->mouse_face_beg_x   = original_x_pixel
 35315                                             - (total_pixel_width + dx);
 35316               hlinfo->mouse_face_end_col = hpos + gseq_length;
 35317               hlinfo->mouse_face_end_x   = 0;
 35318             }
 35319           else
 35320             {
 35321               /* In R2L rows, show_mouse_face expects BEG and END
 35322                  coordinates to be swapped.  */
 35323               hlinfo->mouse_face_end_col = hpos;
 35324               hlinfo->mouse_face_end_x   = original_x_pixel
 35325                                             - (total_pixel_width + dx);
 35326               hlinfo->mouse_face_beg_col = hpos + gseq_length;
 35327               hlinfo->mouse_face_beg_x   = 0;
 35328             }
 35329 
 35330           hlinfo->mouse_face_beg_row  = vpos;
 35331           hlinfo->mouse_face_end_row  = hlinfo->mouse_face_beg_row;
 35332           hlinfo->mouse_face_past_end = false;
 35333           hlinfo->mouse_face_window   = window;
 35334 
 35335           hlinfo->mouse_face_face_id =
 35336             face_at_string_position (w, string, charpos, 0, &ignore,
 35337                                      glyph->face_id, true, 0);
 35338 
 35339           show_mouse_face (hlinfo, DRAW_MOUSE_FACE);
 35340           mouse_face_shown = true;
 35341 
 35342           if (NILP (pointer))
 35343             pointer = Qhand;
 35344         }
 35345     }
 35346 
 35347   /* If mouse-face doesn't need to be shown, clear any existing
 35348      mouse-face.  */
 35349   if ((area == ON_MODE_LINE || area == ON_HEADER_LINE
 35350        || area == ON_TAB_LINE) && !mouse_face_shown)
 35351     clear_mouse_face (hlinfo);
 35352 
 35353   define_frame_cursor1 (f, cursor, pointer);
 35354 }
 35355 
 35356 
 35357 /* EXPORT:
 35358    Take proper action when the mouse has moved to position X, Y on
 35359    frame F with regards to highlighting portions of display that have
 35360    mouse-face properties.  Also de-highlight portions of display where
 35361    the mouse was before, set the mouse pointer shape as appropriate
 35362    for the mouse coordinates, and activate help echo (tooltips).
 35363    X and Y can be negative or out of range.  */
 35364 
 35365 void
 35366 note_mouse_highlight (struct frame *f, int x, int y)
 35367 {
 35368   Mouse_HLInfo *hlinfo = MOUSE_HL_INFO (f);
 35369   enum window_part part = ON_NOTHING;
 35370   Lisp_Object window;
 35371   struct window *w;
 35372   Emacs_Cursor cursor = No_Cursor;
 35373   Lisp_Object pointer = Qnil;  /* Takes precedence over cursor!  */
 35374   struct buffer *b;
 35375 
 35376   /* When a menu is active, don't highlight because this looks odd.  */
 35377 #if defined (HAVE_X_WINDOWS) || defined (HAVE_NS) || defined (MSDOS) \
 35378   || defined (HAVE_ANDROID)
 35379   if (popup_activated ())
 35380     return;
 35381 #endif
 35382 
 35383 #if defined (HAVE_HAIKU)
 35384   if (popup_activated_p)
 35385     return;
 35386 #endif
 35387 
 35388   if (!f->glyphs_initialized_p
 35389       || f->pointer_invisible)
 35390     return;
 35391 
 35392   hlinfo->mouse_face_mouse_x = x;
 35393   hlinfo->mouse_face_mouse_y = y;
 35394   hlinfo->mouse_face_mouse_frame = f;
 35395 
 35396   if (hlinfo->mouse_face_defer)
 35397     return;
 35398 
 35399   /* Which window is that in?  */
 35400   window = window_from_coordinates (f, x, y, &part, true, true);
 35401 
 35402   /* If displaying active text in another window, clear that.  */
 35403   if (! EQ (window, hlinfo->mouse_face_window)
 35404       /* Also clear if we move out of text area in same window.  */
 35405       || (!NILP (hlinfo->mouse_face_window)
 35406           && !NILP (window)
 35407           && part != ON_TEXT
 35408           && part != ON_MODE_LINE
 35409           && part != ON_HEADER_LINE
 35410           && part != ON_TAB_LINE))
 35411     clear_mouse_face (hlinfo);
 35412 
 35413   /* Reset help_echo_string.  It will get recomputed below.  */
 35414   help_echo_string = Qnil;
 35415 
 35416   /* Handle tab-bar highlight on mouse-capable TTY frames.  */
 35417   if (!FRAME_WINDOW_P (f)
 35418       && (y >= FRAME_MENU_BAR_LINES (f)
 35419           && y < FRAME_MENU_BAR_LINES (f) + FRAME_TAB_BAR_LINES (f)))
 35420     {
 35421       int prop_idx;
 35422       bool ignore;
 35423       Lisp_Object caption = tty_get_tab_bar_item (f, x, &prop_idx, &ignore);
 35424 
 35425       if (!NILP (caption))
 35426         {
 35427           help_echo_object = help_echo_window = Qnil;
 35428           help_echo_pos = -1;
 35429           help_echo_string = AREF (f->tab_bar_items,
 35430                                    prop_idx * TAB_BAR_ITEM_NSLOTS
 35431                                    + TAB_BAR_ITEM_HELP);
 35432           if (NILP (help_echo_string))
 35433             help_echo_string = caption;
 35434         }
 35435     }
 35436 
 35437 #ifdef HAVE_WINDOW_SYSTEM
 35438   /* If the cursor is on the internal border of FRAME and FRAME's
 35439      internal border is draggable, provide some visual feedback.  */
 35440   if (FRAME_INTERNAL_BORDER_WIDTH (f) > 0
 35441       && !NILP (get_frame_param (f, Qdrag_internal_border)))
 35442     {
 35443       enum internal_border_part part = frame_internal_border_part (f, x, y);
 35444 
 35445       switch (part)
 35446         {
 35447         case INTERNAL_BORDER_NONE:
 35448           if (cursor != FRAME_OUTPUT_DATA (f)->nontext_cursor)
 35449             /* Reset cursor.  */
 35450             cursor = FRAME_OUTPUT_DATA (f)->nontext_cursor;
 35451           break;
 35452         case INTERNAL_BORDER_LEFT_EDGE:
 35453           cursor = FRAME_OUTPUT_DATA (f)->left_edge_cursor;
 35454           break;
 35455         case INTERNAL_BORDER_TOP_LEFT_CORNER:
 35456           cursor = FRAME_OUTPUT_DATA (f)->top_left_corner_cursor;
 35457           break;
 35458         case INTERNAL_BORDER_TOP_EDGE:
 35459           cursor = FRAME_OUTPUT_DATA (f)->top_edge_cursor;
 35460           break;
 35461         case INTERNAL_BORDER_TOP_RIGHT_CORNER:
 35462           cursor = FRAME_OUTPUT_DATA (f)->top_right_corner_cursor;
 35463           break;
 35464         case INTERNAL_BORDER_RIGHT_EDGE:
 35465           cursor = FRAME_OUTPUT_DATA (f)->right_edge_cursor;
 35466           break;
 35467         case INTERNAL_BORDER_BOTTOM_RIGHT_CORNER:
 35468           cursor = FRAME_OUTPUT_DATA (f)->bottom_right_corner_cursor;
 35469           break;
 35470         case INTERNAL_BORDER_BOTTOM_EDGE:
 35471           cursor = FRAME_OUTPUT_DATA (f)->bottom_edge_cursor;
 35472           break;
 35473         case INTERNAL_BORDER_BOTTOM_LEFT_CORNER:
 35474           cursor = FRAME_OUTPUT_DATA (f)->bottom_left_corner_cursor;
 35475           break;
 35476         default:
 35477           /* This should not happen.  */
 35478           if (cursor != FRAME_OUTPUT_DATA (f)->nontext_cursor)
 35479             cursor = FRAME_OUTPUT_DATA (f)->nontext_cursor;
 35480         }
 35481 
 35482       if (cursor != FRAME_OUTPUT_DATA (f)->nontext_cursor)
 35483         {
 35484           /* Do we really want a help echo here?  */
 35485           help_echo_string = build_string ("drag-mouse-1: resize frame");
 35486           goto set_cursor;
 35487         }
 35488     }
 35489 #endif /* HAVE_WINDOW_SYSTEM */
 35490 
 35491   /* Not on a window -> return.  */
 35492   if (!WINDOWP (window))
 35493     return;
 35494 
 35495   /* Convert to window-relative pixel coordinates.  */
 35496   w = XWINDOW (window);
 35497   frame_to_window_pixel_xy (w, &x, &y);
 35498 
 35499 #if defined (HAVE_WINDOW_SYSTEM)
 35500   /* Handle tab-bar window differently since it doesn't display a
 35501      buffer.  */
 35502   if (EQ (window, f->tab_bar_window))
 35503     {
 35504       note_tab_bar_highlight (f, x, y);
 35505       if (tab_bar__dragging_in_progress)
 35506         {
 35507           cursor = FRAME_OUTPUT_DATA (f)->hand_cursor;
 35508           goto set_cursor;
 35509         }
 35510       else
 35511         return;
 35512     }
 35513   else
 35514     {
 35515       /* The mouse might have pressed into the tab bar, but might
 35516          also have been released outside the tab bar, so
 35517          f->last_tab_bar_item must be reset, in order to make sure the
 35518          item can be still highlighted again in the future.  */
 35519       f->last_tab_bar_item = -1;
 35520     }
 35521 #endif
 35522 
 35523 #if defined (HAVE_WINDOW_SYSTEM) && ! defined (HAVE_EXT_TOOL_BAR)
 35524   /* Handle tool-bar window differently since it doesn't display a
 35525      buffer.  */
 35526   if (EQ (window, f->tool_bar_window))
 35527     {
 35528       note_tool_bar_highlight (f, x, y);
 35529       return;
 35530     }
 35531 #endif
 35532 
 35533   /* Mouse is on the mode, header line or margin?  */
 35534   if (part == ON_MODE_LINE || part == ON_HEADER_LINE || part == ON_TAB_LINE
 35535       || part == ON_LEFT_MARGIN || part == ON_RIGHT_MARGIN)
 35536     {
 35537       note_mode_line_or_margin_highlight (window, x, y, part);
 35538 
 35539 #ifdef HAVE_WINDOW_SYSTEM
 35540       if (part == ON_LEFT_MARGIN || part == ON_RIGHT_MARGIN)
 35541         {
 35542           cursor = FRAME_OUTPUT_DATA (f)->nontext_cursor;
 35543           /* Show non-text cursor (Bug#16647).  */
 35544           goto set_cursor;
 35545         }
 35546       else
 35547 #endif
 35548         return;
 35549     }
 35550 
 35551 #ifdef HAVE_WINDOW_SYSTEM
 35552   if (part == ON_VERTICAL_BORDER)
 35553     {
 35554       cursor = FRAME_OUTPUT_DATA (f)->horizontal_drag_cursor;
 35555       help_echo_string = build_string ("drag-mouse-1: resize");
 35556       goto set_cursor;
 35557     }
 35558   else if (part == ON_RIGHT_DIVIDER)
 35559     {
 35560       cursor = FRAME_OUTPUT_DATA (f)->horizontal_drag_cursor;
 35561       help_echo_string = build_string ("drag-mouse-1: resize");
 35562       goto set_cursor;
 35563     }
 35564   else if (part == ON_BOTTOM_DIVIDER)
 35565     if (! WINDOW_BOTTOMMOST_P (w)
 35566         || minibuf_level
 35567         || NILP (Vresize_mini_windows))
 35568       {
 35569         cursor = FRAME_OUTPUT_DATA (f)->vertical_drag_cursor;
 35570         help_echo_string = build_string ("drag-mouse-1: resize");
 35571         goto set_cursor;
 35572       }
 35573     else
 35574       cursor = FRAME_OUTPUT_DATA (f)->nontext_cursor;
 35575   else if (part == ON_LEFT_FRINGE || part == ON_RIGHT_FRINGE
 35576            || part == ON_VERTICAL_SCROLL_BAR
 35577            || part == ON_HORIZONTAL_SCROLL_BAR)
 35578     cursor = FRAME_OUTPUT_DATA (f)->nontext_cursor;
 35579   else
 35580     cursor = FRAME_OUTPUT_DATA (f)->text_cursor;
 35581 #endif
 35582 
 35583   /* Are we in a window whose display is up to date?
 35584      And verify the buffer's text has not changed.  */
 35585   b = XBUFFER (w->contents);
 35586   if (part == ON_TEXT && w->window_end_valid && !window_outdated (w))
 35587     {
 35588       int hpos, vpos, dx, dy, area = LAST_AREA;
 35589       ptrdiff_t pos;
 35590       struct glyph *glyph;
 35591       Lisp_Object object;
 35592       Lisp_Object mouse_face = Qnil, position;
 35593       Lisp_Object *overlay_vec = NULL;
 35594       ptrdiff_t i, noverlays;
 35595       struct buffer *obuf;
 35596       ptrdiff_t obegv, ozv;
 35597       bool same_region;
 35598 
 35599       /* Find the glyph under X/Y.  */
 35600       glyph = x_y_to_hpos_vpos (w, x, y, &hpos, &vpos, &dx, &dy, &area);
 35601 
 35602 #ifdef HAVE_WINDOW_SYSTEM
 35603       /* Look for :pointer property on image.  */
 35604       if (glyph != NULL && glyph->type == IMAGE_GLYPH)
 35605         {
 35606           struct image *img = IMAGE_OPT_FROM_ID (f, glyph->u.img_id);
 35607           if (img != NULL && IMAGEP (img->spec))
 35608             {
 35609               Lisp_Object image_map, hotspot;
 35610               if ((image_map = plist_get (XCDR (img->spec), QCmap),
 35611                    !NILP (image_map))
 35612                   && (hotspot = find_hot_spot (image_map,
 35613                                                glyph->slice.img.x + dx,
 35614                                                glyph->slice.img.y + dy),
 35615                       CONSP (hotspot))
 35616                   && (hotspot = XCDR (hotspot), CONSP (hotspot)))
 35617                 {
 35618                   Lisp_Object plist;
 35619 
 35620                   /* Could check XCAR (hotspot) to see if we enter/leave
 35621                      this hot-spot.
 35622                      If so, we could look for mouse-enter, mouse-leave
 35623                      properties in PLIST (and do something...).  */
 35624                   hotspot = XCDR (hotspot);
 35625                   if (CONSP (hotspot)
 35626                       && (plist = XCAR (hotspot), CONSP (plist)))
 35627                     {
 35628                       pointer = plist_get (plist, Qpointer);
 35629                       if (NILP (pointer))
 35630                         pointer = Qhand;
 35631                       help_echo_string = plist_get (plist, Qhelp_echo);
 35632                       if (!NILP (help_echo_string))
 35633                         {
 35634                           help_echo_window = window;
 35635                           help_echo_object = glyph->object;
 35636                           help_echo_pos = glyph->charpos;
 35637                         }
 35638                     }
 35639                 }
 35640               if (NILP (pointer))
 35641                 pointer = plist_get (XCDR (img->spec), QCpointer);
 35642             }
 35643         }
 35644 #endif  /* HAVE_WINDOW_SYSTEM */
 35645 
 35646       /* Clear mouse face if X/Y not over text.  */
 35647       if (glyph == NULL
 35648           || area != TEXT_AREA
 35649           || !MATRIX_ROW_DISPLAYS_TEXT_P (MATRIX_ROW (w->current_matrix, vpos))
 35650           /* Glyph's OBJECT is nil for glyphs inserted by the
 35651              display engine for its internal purposes, like truncation
 35652              and continuation glyphs and blanks beyond the end of
 35653              line's text on text terminals.  If we are over such a
 35654              glyph, we are not over any text.  */
 35655           || NILP (glyph->object)
 35656           /* R2L rows have a stretch glyph at their front, which
 35657              stands for no text, whereas L2R rows have no glyphs at
 35658              all beyond the end of text.  Treat such stretch glyphs
 35659              like we do with NULL glyphs in L2R rows.  */
 35660           || (MATRIX_ROW (w->current_matrix, vpos)->reversed_p
 35661               && glyph == MATRIX_ROW_GLYPH_START (w->current_matrix, vpos)
 35662               && glyph->type == STRETCH_GLYPH
 35663               && glyph->avoid_cursor_p))
 35664         {
 35665           if (clear_mouse_face (hlinfo))
 35666             cursor = No_Cursor;
 35667           if (FRAME_WINDOW_P (f) && NILP (pointer))
 35668             {
 35669 #ifdef HAVE_WINDOW_SYSTEM
 35670               if (area != TEXT_AREA)
 35671                 cursor = FRAME_OUTPUT_DATA (f)->nontext_cursor;
 35672               else
 35673                 pointer = Vvoid_text_area_pointer;
 35674 #endif
 35675             }
 35676           goto set_cursor;
 35677         }
 35678 
 35679       pos = glyph->charpos;
 35680       object = glyph->object;
 35681       if (!STRINGP (object) && !BUFFERP (object))
 35682         goto set_cursor;
 35683 
 35684       /* If we get an out-of-range value, return now; avoid an error.  */
 35685       if (BUFFERP (object) && pos > BUF_Z (b))
 35686         goto set_cursor;
 35687 
 35688       /* Make the window's buffer temporarily current for
 35689          overlays_at and compute_char_face.  */
 35690       obuf = current_buffer;
 35691       current_buffer = b;
 35692       obegv = BEGV;
 35693       ozv = ZV;
 35694       BEGV = BEG;
 35695       ZV = Z;
 35696 
 35697       /* Is this char mouse-active or does it have help-echo?  */
 35698       position = make_fixnum (pos);
 35699 
 35700       USE_SAFE_ALLOCA;
 35701 
 35702       if (BUFFERP (object))
 35703         {
 35704           /* Put all the overlays we want in a vector in overlay_vec.  */
 35705           GET_OVERLAYS_AT (pos, overlay_vec, noverlays, NULL);
 35706           /* Sort overlays into increasing priority order.  */
 35707           noverlays = sort_overlays (overlay_vec, noverlays, w);
 35708         }
 35709       else
 35710         noverlays = 0;
 35711 
 35712       if (NILP (Vmouse_highlight))
 35713         {
 35714           clear_mouse_face (hlinfo);
 35715           goto check_help_echo;
 35716         }
 35717 
 35718       same_region = coords_in_mouse_face_p (w, hpos, vpos);
 35719 
 35720       if (same_region)
 35721         cursor = No_Cursor;
 35722 
 35723       /* Check mouse-face highlighting.  */
 35724       if (! same_region
 35725           /* If there exists an overlay with mouse-face overlapping
 35726              the one we are currently highlighting, we have to check
 35727              if we enter the overlapping overlay, and then highlight
 35728              only that.  Skip the check when mouse-face highlighting
 35729              is currently hidden to avoid Bug#30519.  */
 35730           || (!hlinfo->mouse_face_hidden
 35731               && OVERLAYP (hlinfo->mouse_face_overlay)
 35732               /* It's possible the overlay was deleted (Bug#35273).  */
 35733               && OVERLAY_BUFFER (hlinfo->mouse_face_overlay)
 35734               && mouse_face_overlay_overlaps (hlinfo->mouse_face_overlay)))
 35735         {
 35736           /* Find the highest priority overlay with a mouse-face.  */
 35737           Lisp_Object overlay = Qnil;
 35738           for (i = noverlays - 1; i >= 0 && NILP (overlay); --i)
 35739             {
 35740               mouse_face = Foverlay_get (overlay_vec[i], Qmouse_face);
 35741               if (!NILP (mouse_face))
 35742                 overlay = overlay_vec[i];
 35743             }
 35744 
 35745           /* If we're highlighting the same overlay as before, there's
 35746              no need to do that again.  */
 35747           if (!NILP (overlay) && EQ (overlay, hlinfo->mouse_face_overlay))
 35748             goto check_help_echo;
 35749 
 35750           /* Clear the display of the old active region, if any.  */
 35751           if (clear_mouse_face (hlinfo))
 35752             cursor = No_Cursor;
 35753 
 35754           /* Record the overlay, if any, to be highlighted.  */
 35755           hlinfo->mouse_face_overlay = overlay;
 35756 
 35757           /* If no overlay applies, get a text property.  */
 35758           if (NILP (overlay))
 35759             mouse_face = Fget_text_property (position, Qmouse_face, object);
 35760 
 35761           /* Next, compute the bounds of the mouse highlighting and
 35762              display it.  */
 35763           if (!NILP (mouse_face) && STRINGP (object))
 35764             {
 35765               /* The mouse-highlighting comes from a display string
 35766                  with a mouse-face.  */
 35767               Lisp_Object s, e;
 35768               ptrdiff_t ignore;
 35769 
 35770               s = Fprevious_single_property_change
 35771                 (make_fixnum (pos + 1), Qmouse_face, object, Qnil);
 35772               e = Fnext_single_property_change
 35773                 (position, Qmouse_face, object, Qnil);
 35774               if (NILP (s))
 35775                 s = make_fixnum (0);
 35776               if (NILP (e))
 35777                 e = make_fixnum (SCHARS (object));
 35778               mouse_face_from_string_pos (w, hlinfo, object,
 35779                                           XFIXNUM (s), XFIXNUM (e));
 35780               hlinfo->mouse_face_past_end = false;
 35781               hlinfo->mouse_face_window = window;
 35782               hlinfo->mouse_face_face_id
 35783                 = face_at_string_position (w, object, pos, 0, &ignore,
 35784                                            glyph->face_id, true, 0);
 35785               show_mouse_face (hlinfo, DRAW_MOUSE_FACE);
 35786               cursor = No_Cursor;
 35787             }
 35788           else
 35789             {
 35790               /* The mouse-highlighting, if any, comes from an overlay
 35791                  or text property in the buffer.  */
 35792               Lisp_Object buffer UNINIT;
 35793               Lisp_Object disp_string UNINIT;
 35794 
 35795               if (STRINGP (object))
 35796                 {
 35797                   /* If we are on a display string with no mouse-face,
 35798                      check if the text under it has one.  */
 35799                   struct glyph_row *r = MATRIX_ROW (w->current_matrix, vpos);
 35800                   ptrdiff_t start = MATRIX_ROW_START_CHARPOS (r);
 35801                   pos = string_buffer_position (object, start);
 35802                   if (pos > 0)
 35803                     {
 35804                       mouse_face = get_char_property_and_overlay
 35805                         (make_fixnum (pos), Qmouse_face, w->contents, &overlay);
 35806                       buffer = w->contents;
 35807                       disp_string = object;
 35808                     }
 35809                 }
 35810               else
 35811                 {
 35812                   buffer = object;
 35813                   disp_string = Qnil;
 35814                 }
 35815 
 35816               if (!NILP (mouse_face))
 35817                 {
 35818                   Lisp_Object before, after;
 35819                   Lisp_Object before_string, after_string;
 35820                   /* To correctly find the limits of mouse highlight
 35821                      in a bidi-reordered buffer, we must not use the
 35822                      optimization of limiting the search in
 35823                      previous-single-property-change and
 35824                      next-single-property-change, because
 35825                      rows_from_pos_range needs the real start and end
 35826                      positions to DTRT in this case.  That's because
 35827                      the first row visible in a window does not
 35828                      necessarily display the character whose position
 35829                      is the smallest.  */
 35830                   Lisp_Object lim1
 35831                     = NILP (BVAR (XBUFFER (buffer), bidi_display_reordering))
 35832                     ? Fmarker_position (w->start)
 35833                     : Qnil;
 35834                   Lisp_Object lim2
 35835                     = NILP (BVAR (XBUFFER (buffer), bidi_display_reordering))
 35836                     ? make_fixnum (BUF_Z (XBUFFER (buffer))
 35837                                    - w->window_end_pos)
 35838                     : Qnil;
 35839 
 35840                   if (NILP (overlay))
 35841                     {
 35842                       /* Handle the text property case.  */
 35843                       before = Fprevious_single_property_change
 35844                         (make_fixnum (pos + 1), Qmouse_face, buffer, lim1);
 35845                       after = Fnext_single_property_change
 35846                         (make_fixnum (pos), Qmouse_face, buffer, lim2);
 35847                       before_string = after_string = Qnil;
 35848                     }
 35849                   else
 35850                     {
 35851                       /* Handle the overlay case.  */
 35852                       before = Foverlay_start (overlay);
 35853                       after = Foverlay_end (overlay);
 35854                       before_string = Foverlay_get (overlay, Qbefore_string);
 35855                       after_string = Foverlay_get (overlay, Qafter_string);
 35856 
 35857                       if (!STRINGP (before_string)) before_string = Qnil;
 35858                       if (!STRINGP (after_string))  after_string = Qnil;
 35859                     }
 35860 
 35861                   mouse_face_from_buffer_pos (window, hlinfo, pos,
 35862                                               NILP (before)
 35863                                               ? 1
 35864                                               : XFIXNAT (before),
 35865                                               NILP (after)
 35866                                               ? BUF_Z (XBUFFER (buffer))
 35867                                               : XFIXNAT (after),
 35868                                               before_string, after_string,
 35869                                               disp_string);
 35870                   cursor = No_Cursor;
 35871                 }
 35872             }
 35873         }
 35874 
 35875     check_help_echo:
 35876 
 35877       /* Look for a `help-echo' property.  */
 35878       if (NILP (help_echo_string)) {
 35879         Lisp_Object help, overlay;
 35880 
 35881         /* Check overlays first.  */
 35882         help = overlay = Qnil;
 35883         for (i = noverlays - 1; i >= 0 && NILP (help); --i)
 35884           {
 35885             overlay = overlay_vec[i];
 35886             help = Foverlay_get (overlay, Qhelp_echo);
 35887           }
 35888 
 35889         if (!NILP (help))
 35890           {
 35891             help_echo_string = help;
 35892             help_echo_window = window;
 35893             help_echo_object = overlay;
 35894             help_echo_pos = pos;
 35895           }
 35896         else
 35897           {
 35898             Lisp_Object obj = glyph->object;
 35899             ptrdiff_t charpos = glyph->charpos;
 35900 
 35901             /* Try text properties.  */
 35902             if (STRINGP (obj)
 35903                 && charpos >= 0
 35904                 && charpos < SCHARS (obj))
 35905               {
 35906                 help = Fget_text_property (make_fixnum (charpos),
 35907                                            Qhelp_echo, obj);
 35908                 if (NILP (help))
 35909                   {
 35910                     /* If the string itself doesn't specify a help-echo,
 35911                        see if the buffer text ``under'' it does.  */
 35912                     struct glyph_row *r
 35913                       = MATRIX_ROW (w->current_matrix, vpos);
 35914                     ptrdiff_t start = MATRIX_ROW_START_CHARPOS (r);
 35915                     ptrdiff_t p = string_buffer_position (obj, start);
 35916                     if (p > 0)
 35917                       {
 35918                         help = Fget_char_property (make_fixnum (p),
 35919                                                    Qhelp_echo, w->contents);
 35920                         if (!NILP (help))
 35921                           {
 35922                             charpos = p;
 35923                             obj = w->contents;
 35924                           }
 35925                       }
 35926                   }
 35927               }
 35928             else if (BUFFERP (obj)
 35929                      && charpos >= BEGV
 35930                      && charpos < ZV)
 35931               help = Fget_text_property (make_fixnum (charpos), Qhelp_echo,
 35932                                          obj);
 35933 
 35934             if (!NILP (help))
 35935               {
 35936                 help_echo_string = help;
 35937                 help_echo_window = window;
 35938                 help_echo_object = obj;
 35939                 help_echo_pos = charpos;
 35940               }
 35941           }
 35942       }
 35943 
 35944 #ifdef HAVE_WINDOW_SYSTEM
 35945       /* Look for a `pointer' property.  */
 35946       if (FRAME_WINDOW_P (f) && NILP (pointer))
 35947         {
 35948           /* Check overlays first.  */
 35949           for (i = noverlays - 1; i >= 0 && NILP (pointer); --i)
 35950             pointer = Foverlay_get (overlay_vec[i], Qpointer);
 35951 
 35952           if (NILP (pointer))
 35953             {
 35954               Lisp_Object obj = glyph->object;
 35955               ptrdiff_t charpos = glyph->charpos;
 35956 
 35957               /* Try text properties.  */
 35958               if (STRINGP (obj)
 35959                   && charpos >= 0
 35960                   && charpos < SCHARS (obj))
 35961                 {
 35962                   pointer = Fget_text_property (make_fixnum (charpos),
 35963                                                 Qpointer, obj);
 35964                   if (NILP (pointer))
 35965                     {
 35966                       /* If the string itself doesn't specify a pointer,
 35967                          see if the buffer text ``under'' it does.  */
 35968                       struct glyph_row *r
 35969                         = MATRIX_ROW (w->current_matrix, vpos);
 35970                       ptrdiff_t start = MATRIX_ROW_START_CHARPOS (r);
 35971                       ptrdiff_t p = string_buffer_position (obj, start);
 35972                       if (p > 0)
 35973                         pointer = Fget_char_property (make_fixnum (p),
 35974                                                       Qpointer, w->contents);
 35975                     }
 35976                 }
 35977               else if (BUFFERP (obj)
 35978                        && charpos >= BEGV
 35979                        && charpos < ZV)
 35980                 pointer = Fget_text_property (make_fixnum (charpos),
 35981                                               Qpointer, obj);
 35982             }
 35983         }
 35984 #endif  /* HAVE_WINDOW_SYSTEM */
 35985 
 35986       BEGV = obegv;
 35987       ZV = ozv;
 35988       current_buffer = obuf;
 35989       SAFE_FREE ();
 35990     }
 35991 
 35992  set_cursor:
 35993   define_frame_cursor1 (f, cursor, pointer);
 35994 }
 35995 
 35996 
 35997 /* EXPORT for RIF:
 35998    Clear any mouse-face on window W.  This function is part of the
 35999    redisplay interface, and is called from try_window_id and similar
 36000    functions to ensure the mouse-highlight is off.  */
 36001 
 36002 void
 36003 gui_clear_window_mouse_face (struct window *w)
 36004 {
 36005   Mouse_HLInfo *hlinfo = MOUSE_HL_INFO (XFRAME (w->frame));
 36006   Lisp_Object window;
 36007 
 36008   block_input ();
 36009   XSETWINDOW (window, w);
 36010   if (EQ (window, hlinfo->mouse_face_window))
 36011     clear_mouse_face (hlinfo);
 36012   unblock_input ();
 36013 }
 36014 
 36015 
 36016 /* EXPORT:
 36017    Just discard the mouse face information for frame F, if any.
 36018    This is used when the size of F is changed.  */
 36019 
 36020 void
 36021 cancel_mouse_face (struct frame *f)
 36022 {
 36023   Lisp_Object window;
 36024   Mouse_HLInfo *hlinfo = MOUSE_HL_INFO (f);
 36025 
 36026   window = hlinfo->mouse_face_window;
 36027   if (! NILP (window) && XFRAME (XWINDOW (window)->frame) == f)
 36028     reset_mouse_highlight (hlinfo);
 36029 }
 36030 
 36031 
 36032 
 36033 /***********************************************************************
 36034                            Exposure Events
 36035  ***********************************************************************/
 36036 
 36037 #ifdef HAVE_WINDOW_SYSTEM
 36038 
 36039 /* Redraw the part of glyph row area AREA of glyph row ROW on window W
 36040    which intersects rectangle R.  R is in window-relative coordinates.  */
 36041 
 36042 static void
 36043 expose_area (struct window *w, struct glyph_row *row, const Emacs_Rectangle *r,
 36044              enum glyph_row_area area)
 36045 {
 36046   struct glyph *first = row->glyphs[area];
 36047   struct glyph *end = row->glyphs[area] + row->used[area];
 36048   struct glyph *last;
 36049   int first_x, start_x, x;
 36050 
 36051   if (area == TEXT_AREA && row->fill_line_p)
 36052     /* If row extends face to end of line write the whole line.  */
 36053     draw_glyphs (w, row->x, row, area,
 36054                  0, row->used[area],
 36055                  DRAW_NORMAL_TEXT, 0);
 36056   else
 36057     {
 36058       /* Set START_X to the window-relative start position for drawing glyphs of
 36059          AREA.  The first glyph of the text area can be partially visible.
 36060          The first glyphs of other areas cannot.  */
 36061       start_x = window_box_left_offset (w, area);
 36062       x = start_x;
 36063       if (area == TEXT_AREA)
 36064         x += row->x;
 36065 
 36066       /* Find the first glyph that must be redrawn.  */
 36067       while (first < end
 36068              && x + first->pixel_width < r->x)
 36069         {
 36070           x += first->pixel_width;
 36071           ++first;
 36072         }
 36073 
 36074       /* Find the last one.  */
 36075       last = first;
 36076       first_x = x;
 36077       /* Use a signed int intermediate value to avoid catastrophic
 36078          failures due to comparison between signed and unsigned, when
 36079          x is negative (can happen for wide images that are hscrolled).  */
 36080       int r_end = r->x + r->width;
 36081       while (last < end && x < r_end)
 36082         {
 36083           x += last->pixel_width;
 36084           ++last;
 36085         }
 36086 
 36087       /* Repaint.  */
 36088       if (last > first)
 36089         draw_glyphs (w, first_x - start_x, row, area,
 36090                      first - row->glyphs[area], last - row->glyphs[area],
 36091                      DRAW_NORMAL_TEXT, 0);
 36092     }
 36093 }
 36094 
 36095 
 36096 /* Redraw the parts of the glyph row ROW on window W intersecting
 36097    rectangle R.  R is in window-relative coordinates.  Value is
 36098    true if mouse-face was overwritten.  */
 36099 
 36100 static bool
 36101 expose_line (struct window *w, struct glyph_row *row, const Emacs_Rectangle *r)
 36102 {
 36103   eassert (row->enabled_p);
 36104 
 36105   if (row->mode_line_p || w->pseudo_window_p)
 36106     draw_glyphs (w, 0, row, TEXT_AREA,
 36107                  0, row->used[TEXT_AREA],
 36108                  DRAW_NORMAL_TEXT, 0);
 36109   else
 36110     {
 36111       if (row->used[LEFT_MARGIN_AREA])
 36112         expose_area (w, row, r, LEFT_MARGIN_AREA);
 36113       if (row->used[TEXT_AREA])
 36114         expose_area (w, row, r, TEXT_AREA);
 36115       if (row->used[RIGHT_MARGIN_AREA])
 36116         expose_area (w, row, r, RIGHT_MARGIN_AREA);
 36117       draw_row_fringe_bitmaps (w, row);
 36118     }
 36119 
 36120   return row->mouse_face_p;
 36121 }
 36122 
 36123 
 36124 /* Redraw those parts of glyphs rows during expose event handling that
 36125    overlap other rows.  Redrawing of an exposed line writes over parts
 36126    of lines overlapping that exposed line; this function fixes that.
 36127 
 36128    W is the window being exposed.  FIRST_OVERLAPPING_ROW is the first
 36129    row in W's current matrix that is exposed and overlaps other rows.
 36130    LAST_OVERLAPPING_ROW is the last such row.  */
 36131 
 36132 static void
 36133 expose_overlaps (struct window *w,
 36134                  struct glyph_row *first_overlapping_row,
 36135                  struct glyph_row *last_overlapping_row,
 36136                  const Emacs_Rectangle *r)
 36137 {
 36138   struct glyph_row *row;
 36139 
 36140   for (row = first_overlapping_row; row <= last_overlapping_row; ++row)
 36141     if (row->overlapping_p)
 36142       {
 36143         eassert (row->enabled_p && !row->mode_line_p);
 36144 
 36145         row->clip = r;
 36146         if (row->used[LEFT_MARGIN_AREA])
 36147           gui_fix_overlapping_area (w, row, LEFT_MARGIN_AREA, OVERLAPS_BOTH);
 36148 
 36149         if (row->used[TEXT_AREA])
 36150           gui_fix_overlapping_area (w, row, TEXT_AREA, OVERLAPS_BOTH);
 36151 
 36152         if (row->used[RIGHT_MARGIN_AREA])
 36153           gui_fix_overlapping_area (w, row, RIGHT_MARGIN_AREA, OVERLAPS_BOTH);
 36154         row->clip = NULL;
 36155       }
 36156 }
 36157 
 36158 
 36159 /* Return true if W's cursor intersects rectangle R.  */
 36160 
 36161 static bool
 36162 phys_cursor_in_rect_p (struct window *w, const Emacs_Rectangle *r)
 36163 {
 36164   Emacs_Rectangle cr, result;
 36165   struct glyph *cursor_glyph;
 36166   struct glyph_row *row;
 36167 
 36168   if (w->phys_cursor.vpos >= 0
 36169       && w->phys_cursor.vpos < w->current_matrix->nrows
 36170       && (row = MATRIX_ROW (w->current_matrix, w->phys_cursor.vpos),
 36171           row->enabled_p)
 36172       && row->cursor_in_fringe_p)
 36173     {
 36174       /* Cursor is in the fringe.  */
 36175       cr.x = window_box_right_offset (w,
 36176                                       (WINDOW_HAS_FRINGES_OUTSIDE_MARGINS (w)
 36177                                        ? RIGHT_MARGIN_AREA
 36178                                        : TEXT_AREA));
 36179       cr.y = row->y;
 36180       cr.width = WINDOW_RIGHT_FRINGE_WIDTH (w);
 36181       cr.height = row->height;
 36182       return gui_intersect_rectangles (&cr, r, &result);
 36183     }
 36184 
 36185   cursor_glyph = get_phys_cursor_glyph (w);
 36186   if (cursor_glyph)
 36187     {
 36188       /* r is relative to W's box, but w->phys_cursor.x is relative
 36189          to left edge of W's TEXT area.  Adjust it.  */
 36190       cr.x = window_box_left_offset (w, TEXT_AREA) + w->phys_cursor.x;
 36191       cr.y = w->phys_cursor.y;
 36192       cr.width = cursor_glyph->pixel_width;
 36193       cr.height = w->phys_cursor_height;
 36194       /* ++KFS: W32 version used W32-specific IntersectRect here, but
 36195          I assume the effect is the same -- and this is portable.  */
 36196       return gui_intersect_rectangles (&cr, r, &result);
 36197     }
 36198   /* If we don't understand the format, pretend we're not in the hot-spot.  */
 36199   return false;
 36200 }
 36201 
 36202 
 36203 /* EXPORT:
 36204    Draw a vertical window border to the right of window W if W doesn't
 36205    have vertical scroll bars.  */
 36206 
 36207 void
 36208 gui_draw_vertical_border (struct window *w)
 36209 {
 36210   struct frame *f = XFRAME (WINDOW_FRAME (w));
 36211 
 36212   /* We could do better, if we knew what type of scroll-bar the adjacent
 36213      windows (on either side) have...  But we don't :-(
 36214      However, I think this works ok.  ++KFS 2003-04-25 */
 36215 
 36216   /* Redraw borders between horizontally adjacent windows.  Don't
 36217      do it for frames with vertical scroll bars because either the
 36218      right scroll bar of a window, or the left scroll bar of its
 36219      neighbor will suffice as a border.  */
 36220   if (FRAME_HAS_VERTICAL_SCROLL_BARS (f) || FRAME_RIGHT_DIVIDER_WIDTH (f))
 36221     return;
 36222 
 36223   /* Note: It is necessary to redraw both the left and the right
 36224      borders, for when only this single window W is being
 36225      redisplayed.  */
 36226   if (!WINDOW_RIGHTMOST_P (w)
 36227       && !WINDOW_HAS_VERTICAL_SCROLL_BAR_ON_RIGHT (w))
 36228     {
 36229       int x0, x1, y0, y1;
 36230 
 36231       window_box_edges (w, &x0, &y0, &x1, &y1);
 36232       y1 -= 1;
 36233 
 36234       if (WINDOW_LEFT_FRINGE_WIDTH (w) == 0)
 36235         x1 -= 1;
 36236 
 36237       FRAME_RIF (f)->draw_vertical_window_border (w, x1, y0, y1);
 36238     }
 36239 
 36240   if (!WINDOW_LEFTMOST_P (w)
 36241       && !WINDOW_HAS_VERTICAL_SCROLL_BAR_ON_LEFT (w))
 36242     {
 36243       int x0, x1, y0, y1;
 36244 
 36245       window_box_edges (w, &x0, &y0, &x1, &y1);
 36246       y1 -= 1;
 36247 
 36248       if (WINDOW_LEFT_FRINGE_WIDTH (w) == 0)
 36249         x0 -= 1;
 36250 
 36251       FRAME_RIF (f)->draw_vertical_window_border (w, x0, y0, y1);
 36252     }
 36253 }
 36254 
 36255 
 36256 /* Draw window dividers for window W.  */
 36257 
 36258 void
 36259 gui_draw_right_divider (struct window *w)
 36260 {
 36261   struct frame *f = WINDOW_XFRAME (w);
 36262 
 36263   if (w->mini || w->pseudo_window_p)
 36264     return;
 36265   else if (WINDOW_RIGHT_DIVIDER_WIDTH (w))
 36266     {
 36267       int x0 = WINDOW_RIGHT_EDGE_X (w) - WINDOW_RIGHT_DIVIDER_WIDTH (w);
 36268       int x1 = WINDOW_RIGHT_EDGE_X (w);
 36269       int y0 = WINDOW_TOP_EDGE_Y (w);
 36270       int y1 = WINDOW_BOTTOM_EDGE_Y (w);
 36271 
 36272       /* If W is horizontally combined and has a right sibling, don't
 36273          draw over any bottom divider.  */
 36274       if (WINDOW_BOTTOM_DIVIDER_WIDTH (w)
 36275           && !NILP (w->parent)
 36276           && WINDOW_HORIZONTAL_COMBINATION_P (XWINDOW (w->parent))
 36277           && !NILP (w->next))
 36278         y1 -= WINDOW_BOTTOM_DIVIDER_WIDTH (w);
 36279 
 36280       FRAME_RIF (f)->draw_window_divider (w, x0, x1, y0, y1);
 36281     }
 36282 }
 36283 
 36284 static void
 36285 gui_draw_bottom_divider (struct window *w)
 36286 {
 36287   struct frame *f = XFRAME (WINDOW_FRAME (w));
 36288 
 36289   if (w->mini || w->pseudo_window_p)
 36290     return;
 36291   else if (WINDOW_BOTTOM_DIVIDER_WIDTH (w))
 36292     {
 36293       int x0 = WINDOW_LEFT_EDGE_X (w);
 36294       int x1 = WINDOW_RIGHT_EDGE_X (w);
 36295       int y0 = WINDOW_BOTTOM_EDGE_Y (w) - WINDOW_BOTTOM_DIVIDER_WIDTH (w);
 36296       int y1 = WINDOW_BOTTOM_EDGE_Y (w);
 36297       struct window *p = !NILP (w->parent) ? XWINDOW (w->parent) : NULL;
 36298 
 36299       /* If W is vertically combined and has a sibling below, don't draw
 36300          over any right divider.  */
 36301       if (WINDOW_RIGHT_DIVIDER_WIDTH (w)
 36302           && p
 36303           && ((WINDOW_VERTICAL_COMBINATION_P (p)
 36304                && !NILP (w->next))
 36305               || (WINDOW_HORIZONTAL_COMBINATION_P (p)
 36306                   && NILP (w->next)
 36307                   && !NILP (p->parent)
 36308                   && WINDOW_VERTICAL_COMBINATION_P (XWINDOW (p->parent))
 36309                   && !NILP (XWINDOW (p->parent)->next))))
 36310         x1 -= WINDOW_RIGHT_DIVIDER_WIDTH (w);
 36311 
 36312       FRAME_RIF (f)->draw_window_divider (w, x0, x1, y0, y1);
 36313     }
 36314 }
 36315 
 36316 /* Redraw the part of window W intersection rectangle FR.  Pixel
 36317    coordinates in FR are frame-relative.  Call this function with
 36318    input blocked.  Value is true if the exposure overwrites
 36319    mouse-face.  */
 36320 
 36321 static bool
 36322 expose_window (struct window *w, const Emacs_Rectangle *fr)
 36323 {
 36324   struct frame *f = XFRAME (w->frame);
 36325   Emacs_Rectangle wr, r;
 36326   bool mouse_face_overwritten_p = false;
 36327 
 36328   /* If window is not yet fully initialized, do nothing.  This can
 36329      happen when toolkit scroll bars are used and a window is split.
 36330      Reconfiguring the scroll bar will generate an expose for a newly
 36331      created window.  */
 36332   if (w->current_matrix == NULL)
 36333     return false;
 36334 
 36335   /* When we're currently updating the window, display and current
 36336      matrix usually don't agree.  Arrange for a thorough display
 36337      later.  */
 36338   if (w->must_be_updated_p)
 36339     {
 36340       SET_FRAME_GARBAGED (f);
 36341       return false;
 36342     }
 36343 
 36344   /* Frame-relative pixel rectangle of W.  */
 36345   wr.x = WINDOW_LEFT_EDGE_X (w);
 36346   wr.y = WINDOW_TOP_EDGE_Y (w);
 36347   wr.width = WINDOW_PIXEL_WIDTH (w);
 36348   wr.height = WINDOW_PIXEL_HEIGHT (w);
 36349 
 36350   if (gui_intersect_rectangles (fr, &wr, &r))
 36351     {
 36352       int yb = window_text_bottom_y (w);
 36353       struct glyph_row *row;
 36354       struct glyph_row *first_overlapping_row, *last_overlapping_row;
 36355 
 36356       redisplay_trace ("expose_window (%d, %d, %u, %u)\n",
 36357                        r.x, r.y, r.width, r.height);
 36358 
 36359       /* Convert to window coordinates.  */
 36360       r.x -= WINDOW_LEFT_EDGE_X (w);
 36361       r.y -= WINDOW_TOP_EDGE_Y (w);
 36362 
 36363       /* Turn off the cursor.  */
 36364       bool cursor_cleared_p = (!w->pseudo_window_p
 36365                                && phys_cursor_in_rect_p (w, &r));
 36366       if (cursor_cleared_p)
 36367         gui_clear_cursor (w);
 36368 
 36369       /* If the row containing the cursor extends face to end of line,
 36370          then expose_area might overwrite the cursor outside the
 36371          rectangle and thus notice_overwritten_cursor might clear
 36372          w->phys_cursor_on_p.  We remember the original value and
 36373          check later if it is changed.  */
 36374       bool phys_cursor_on_p = w->phys_cursor_on_p;
 36375 
 36376       /* Use a signed int intermediate value to avoid catastrophic
 36377          failures due to comparison between signed and unsigned, when
 36378          y0 or y1 is negative (can happen for tall images).  */
 36379       int r_bottom = r.y + r.height;
 36380 
 36381       /* We must temporarily switch to the window's buffer, in case
 36382          the fringe face has been remapped in that buffer's
 36383          face-remapping-alist, so that draw_row_fringe_bitmaps,
 36384          called from expose_line, will use the right face.  */
 36385       bool buffer_changed = false;
 36386       struct buffer *oldbuf = current_buffer;
 36387       if (!w->pseudo_window_p)
 36388         {
 36389           set_buffer_internal_1 (XBUFFER (w->contents));
 36390           buffer_changed = true;
 36391         }
 36392 
 36393       /* Update lines intersecting rectangle R.  */
 36394       first_overlapping_row = last_overlapping_row = NULL;
 36395       for (row = w->current_matrix->rows;
 36396            row->enabled_p;
 36397            ++row)
 36398         {
 36399           int y0 = row->y;
 36400           int y1 = MATRIX_ROW_BOTTOM_Y (row);
 36401 
 36402           if ((y0 >= r.y && y0 < r_bottom)
 36403               || (y1 > r.y && y1 < r_bottom)
 36404               || (r.y >= y0 && r.y < y1)
 36405               || (r_bottom > y0 && r_bottom < y1))
 36406             {
 36407               /* A header line may be overlapping, but there is no need
 36408                  to fix overlapping areas for them.  KFS 2005-02-12 */
 36409               if (row->overlapping_p && !row->mode_line_p)
 36410                 {
 36411                   if (first_overlapping_row == NULL)
 36412                     first_overlapping_row = row;
 36413                   last_overlapping_row = row;
 36414                 }
 36415 
 36416               row->clip = fr;
 36417               if (expose_line (w, row, &r))
 36418                 mouse_face_overwritten_p = true;
 36419               row->clip = NULL;
 36420             }
 36421           else if (row->overlapping_p)
 36422             {
 36423               /* We must redraw a row overlapping the exposed area.  */
 36424               if (y0 < r.y
 36425                   ? y0 + row->phys_height > r.y
 36426                   : y0 + row->ascent - row->phys_ascent < r.y +r.height)
 36427                 {
 36428                   if (first_overlapping_row == NULL)
 36429                     first_overlapping_row = row;
 36430                   last_overlapping_row = row;
 36431                 }
 36432             }
 36433 
 36434           if (y1 >= yb)
 36435             break;
 36436         }
 36437 
 36438       if (buffer_changed)
 36439         set_buffer_internal_1 (oldbuf);
 36440 
 36441       /* Display the mode line if there is one.  */
 36442       if (window_wants_mode_line (w)
 36443           && (row = MATRIX_MODE_LINE_ROW (w->current_matrix),
 36444               row->enabled_p)
 36445           && row->y < r_bottom)
 36446         {
 36447           if (expose_line (w, row, &r))
 36448             mouse_face_overwritten_p = true;
 36449         }
 36450 
 36451       if (!w->pseudo_window_p)
 36452         {
 36453           /* Fix the display of overlapping rows.  */
 36454           if (first_overlapping_row)
 36455             expose_overlaps (w, first_overlapping_row, last_overlapping_row,
 36456                              fr);
 36457 
 36458           /* Draw border between windows.  */
 36459           if (WINDOW_RIGHT_DIVIDER_WIDTH (w))
 36460             gui_draw_right_divider (w);
 36461           else
 36462             gui_draw_vertical_border (w);
 36463 
 36464           if (WINDOW_BOTTOM_DIVIDER_WIDTH (w))
 36465             gui_draw_bottom_divider (w);
 36466 
 36467           /* Turn the cursor on again.  */
 36468           if (cursor_cleared_p
 36469               || (phys_cursor_on_p && !w->phys_cursor_on_p))
 36470             update_window_cursor (w, true);
 36471         }
 36472     }
 36473 
 36474   return mouse_face_overwritten_p;
 36475 }
 36476 
 36477 
 36478 
 36479 /* Redraw (parts) of all windows in the window tree rooted at W that
 36480    intersect R.  R contains frame pixel coordinates.  Value is
 36481    true if the exposure overwrites mouse-face.  */
 36482 
 36483 static bool
 36484 expose_window_tree (struct window *w, const Emacs_Rectangle *r)
 36485 {
 36486   struct frame *f = XFRAME (w->frame);
 36487   bool mouse_face_overwritten_p = false;
 36488 
 36489   while (w && !FRAME_GARBAGED_P (f))
 36490     {
 36491       mouse_face_overwritten_p
 36492         |= (WINDOWP (w->contents)
 36493             ? expose_window_tree (XWINDOW (w->contents), r)
 36494             : expose_window (w, r));
 36495 
 36496       w = NILP (w->next) ? NULL : XWINDOW (w->next);
 36497     }
 36498 
 36499   return mouse_face_overwritten_p;
 36500 }
 36501 
 36502 
 36503 /* EXPORT:
 36504    Redisplay an exposed area of frame F.  X and Y are the upper-left
 36505    corner of the exposed rectangle.  W and H are width and height of
 36506    the exposed area.  All are pixel values.  W or H zero means redraw
 36507    the entire frame.  */
 36508 
 36509 void
 36510 expose_frame (struct frame *f, int x, int y, int w, int h)
 36511 {
 36512   Emacs_Rectangle r;
 36513   bool mouse_face_overwritten_p = false;
 36514 
 36515   if (FRAME_GARBAGED_P (f))
 36516     {
 36517       redisplay_trace ("expose_frame garbaged\n");
 36518       return;
 36519     }
 36520 
 36521   /* If basic faces haven't been realized yet, there is no point in
 36522      trying to redraw anything.  This can happen when we get an expose
 36523      event while Emacs is starting, e.g. by moving another window.  */
 36524   if (FRAME_FACE_CACHE (f) == NULL
 36525       || FRAME_FACE_CACHE (f)->used < BASIC_FACE_ID_SENTINEL)
 36526     {
 36527       redisplay_trace ("expose_frame no faces\n");
 36528       return;
 36529     }
 36530 
 36531   if (w == 0 || h == 0)
 36532     {
 36533       r.x = r.y = 0;
 36534       r.width = FRAME_TEXT_WIDTH (f);
 36535       r.height = FRAME_TEXT_HEIGHT (f);
 36536     }
 36537   else
 36538     {
 36539       r.x = x;
 36540       r.y = y;
 36541       r.width = w;
 36542       r.height = h;
 36543     }
 36544 
 36545   redisplay_trace ("expose_frame (%d, %d, %u, %u)\n",
 36546                    r.x, r.y, r.width, r.height);
 36547   mouse_face_overwritten_p = expose_window_tree (XWINDOW (f->root_window), &r);
 36548 
 36549   if (WINDOWP (f->tab_bar_window))
 36550     mouse_face_overwritten_p
 36551       |= expose_window (XWINDOW (f->tab_bar_window), &r);
 36552 
 36553 #ifndef HAVE_EXT_TOOL_BAR
 36554   if (WINDOWP (f->tool_bar_window))
 36555     mouse_face_overwritten_p
 36556       |= expose_window (XWINDOW (f->tool_bar_window), &r);
 36557 #endif
 36558 
 36559 #if defined HAVE_WINDOW_SYSTEM && !defined HAVE_EXT_MENU_BAR
 36560   if (WINDOWP (f->menu_bar_window))
 36561     mouse_face_overwritten_p
 36562       |= expose_window (XWINDOW (f->menu_bar_window), &r);
 36563 #endif
 36564 
 36565   /* Some window managers support a focus-follows-mouse style with
 36566      delayed raising of frames.  Imagine a partially obscured frame,
 36567      and moving the mouse into partially obscured mouse-face on that
 36568      frame.  The visible part of the mouse-face will be highlighted,
 36569      then the WM raises the obscured frame.  With at least one WM, KDE
 36570      2.1, Emacs is not getting any event for the raising of the frame
 36571      (even tried with SubstructureRedirectMask), only Expose events.
 36572      These expose events will draw text normally, i.e. not
 36573      highlighted.  Which means we must redo the highlight here.
 36574      Subsume it under ``we love X''.  --gerd 2001-08-15  */
 36575   /* Included in Windows version because Windows most likely does not
 36576      do the right thing if any third party tool offers
 36577      focus-follows-mouse with delayed raise.  --jason 2001-10-12  */
 36578   if (mouse_face_overwritten_p && !FRAME_GARBAGED_P (f))
 36579     {
 36580       Mouse_HLInfo *hlinfo = MOUSE_HL_INFO (f);
 36581       if (f == hlinfo->mouse_face_mouse_frame)
 36582         {
 36583           int mouse_x = hlinfo->mouse_face_mouse_x;
 36584           int mouse_y = hlinfo->mouse_face_mouse_y;
 36585           clear_mouse_face (hlinfo);
 36586           note_mouse_highlight (f, mouse_x, mouse_y);
 36587         }
 36588     }
 36589 }
 36590 
 36591 
 36592 /* EXPORT:
 36593    Determine the intersection of two rectangles R1 and R2.  Return
 36594    the intersection in *RESULT.  Value is true if RESULT is not
 36595    empty.  */
 36596 
 36597 bool
 36598 gui_intersect_rectangles (const Emacs_Rectangle *r1, const Emacs_Rectangle *r2,
 36599                           Emacs_Rectangle *result)
 36600 {
 36601   const Emacs_Rectangle *left, *right;
 36602   const Emacs_Rectangle *upper, *lower;
 36603   bool intersection_p = false;
 36604 
 36605   /* Rearrange so that R1 is the left-most rectangle.  */
 36606   if (r1->x < r2->x)
 36607     left = r1, right = r2;
 36608   else
 36609     left = r2, right = r1;
 36610 
 36611   /* X0 of the intersection is right.x0, if this is inside R1,
 36612      otherwise there is no intersection.  */
 36613   if (right->x <= left->x + left->width)
 36614     {
 36615       result->x = right->x;
 36616 
 36617       /* The right end of the intersection is the minimum of
 36618          the right ends of left and right.  */
 36619       result->width = (min (left->x + left->width, right->x + right->width)
 36620                        - result->x);
 36621 
 36622       /* Same game for Y.  */
 36623       if (r1->y < r2->y)
 36624         upper = r1, lower = r2;
 36625       else
 36626         upper = r2, lower = r1;
 36627 
 36628       /* The upper end of the intersection is lower.y0, if this is inside
 36629          of upper.  Otherwise, there is no intersection.  */
 36630       if (lower->y <= upper->y + upper->height)
 36631         {
 36632           result->y = lower->y;
 36633 
 36634           /* The lower end of the intersection is the minimum of the lower
 36635              ends of upper and lower.  */
 36636           result->height = (min (lower->y + lower->height,
 36637                                  upper->y + upper->height)
 36638                             - result->y);
 36639           intersection_p = true;
 36640         }
 36641     }
 36642 
 36643   return intersection_p;
 36644 }
 36645 
 36646 /* EXPORT:
 36647    Determine the union of the rectangles A and B.  Return the smallest
 36648    rectangle encompassing both the bounds of A and B in *RESULT.  It
 36649    is safe for all three arguments to point to each other.  */
 36650 
 36651 void
 36652 gui_union_rectangles (const Emacs_Rectangle *a, const Emacs_Rectangle *b,
 36653                       Emacs_Rectangle *result)
 36654 {
 36655   struct gui_box a_box, b_box, result_box;
 36656 
 36657   /* Handle special cases where one of the rectangles is empty.  */
 36658 
 36659   if (!a->width || !a->height)
 36660     {
 36661       *result = *b;
 36662       return;
 36663     }
 36664   else if (!b->width || !b->height)
 36665     {
 36666       *result = *a;
 36667       return;
 36668     }
 36669 
 36670   /* Convert A and B to boxes.  */
 36671   a_box.x1 = a->x;
 36672   a_box.y1 = a->y;
 36673   a_box.x2 = a->x + a->width;
 36674   a_box.y2 = a->y + a->height;
 36675 
 36676   b_box.x1 = b->x;
 36677   b_box.y1 = b->y;
 36678   b_box.x2 = b->x + b->width;
 36679   b_box.y2 = b->y + b->height;
 36680 
 36681   /* Compute the union of the boxes.  */
 36682   result_box.x1 = min (a_box.x1, b_box.x1);
 36683   result_box.y1 = min (a_box.y1, b_box.y1);
 36684   result_box.x2 = max (a_box.x2, b_box.x2);
 36685   result_box.y2 = max (a_box.y2, b_box.y2);
 36686 
 36687   /* Convert result_box to an XRectangle and put the result in
 36688      RESULT.  */
 36689   result->x = result_box.x1;
 36690   result->y = result_box.y1;
 36691   result->width = result_box.x2 - result_box.x1;
 36692   result->height = result_box.y2 - result_box.y1;
 36693 }
 36694 
 36695 #endif /* HAVE_WINDOW_SYSTEM */
 36696 
 36697 
 36698 /***********************************************************************
 36699                             Initialization
 36700  ***********************************************************************/
 36701 
 36702 void
 36703 syms_of_xdisp (void)
 36704 {
 36705   Vwith_echo_area_save_vector = Qnil;
 36706   staticpro (&Vwith_echo_area_save_vector);
 36707 
 36708   Vmessage_stack = Qnil;
 36709   staticpro (&Vmessage_stack);
 36710 
 36711   /* Non-nil means don't actually do any redisplay.  */
 36712   DEFSYM (Qinhibit_redisplay, "inhibit-redisplay");
 36713 
 36714   DEFSYM (Qredisplay_internal_xC_functionx, "redisplay_internal (C function)");
 36715 
 36716   DEFVAR_BOOL ("scroll-minibuffer-conservatively",
 36717                scroll_minibuffer_conservatively,
 36718                doc: /* Non-nil means scroll conservatively in minibuffer windows.
 36719 When the value is nil, scrolling in minibuffer windows obeys the
 36720 settings of `scroll-conservatively'.  */);
 36721   scroll_minibuffer_conservatively = true; /* bug#44070 */
 36722 
 36723   DEFVAR_BOOL ("inhibit-message", inhibit_message,
 36724               doc:  /* Non-nil means calls to `message' are not displayed.
 36725 They are still logged to the *Messages* buffer.
 36726 
 36727 Do NOT set this globally to a non-nil value, as doing that will
 36728 disable messages everywhere, including in I-search and other
 36729 places where they are necessary.  This variable is intended to
 36730 be let-bound around code that needs to disable messages temporarily. */);
 36731   inhibit_message = false;
 36732 
 36733   message_dolog_marker1 = Fmake_marker ();
 36734   staticpro (&message_dolog_marker1);
 36735   message_dolog_marker2 = Fmake_marker ();
 36736   staticpro (&message_dolog_marker2);
 36737   message_dolog_marker3 = Fmake_marker ();
 36738   staticpro (&message_dolog_marker3);
 36739 
 36740   defsubr (&Sset_buffer_redisplay);
 36741 #ifdef GLYPH_DEBUG
 36742   defsubr (&Sdump_frame_glyph_matrix);
 36743   defsubr (&Sdump_glyph_matrix);
 36744   defsubr (&Sdump_glyph_row);
 36745   defsubr (&Sdump_tab_bar_row);
 36746   defsubr (&Sdump_tool_bar_row);
 36747   defsubr (&Strace_redisplay);
 36748   defsubr (&Strace_to_stderr);
 36749 #endif
 36750 #ifdef HAVE_WINDOW_SYSTEM
 36751   defsubr (&Stab_bar_height);
 36752   defsubr (&Stool_bar_height);
 36753   defsubr (&Slookup_image_map);
 36754 #endif
 36755   defsubr (&Sline_pixel_height);
 36756   defsubr (&Sformat_mode_line);
 36757   defsubr (&Sinvisible_p);
 36758   defsubr (&Scurrent_bidi_paragraph_direction);
 36759   defsubr (&Swindow_text_pixel_size);
 36760   defsubr (&Sbuffer_text_pixel_size);
 36761   defsubr (&Smove_point_visually);
 36762   defsubr (&Sbidi_find_overridden_directionality);
 36763   defsubr (&Sdisplay__line_is_continued_p);
 36764   defsubr (&Sget_display_property);
 36765   defsubr (&Slong_line_optimizations_p);
 36766 
 36767   DEFSYM (Qmenu_bar_update_hook, "menu-bar-update-hook");
 36768   DEFSYM (Qoverriding_terminal_local_map, "overriding-terminal-local-map");
 36769   DEFSYM (Qoverriding_local_map, "overriding-local-map");
 36770   DEFSYM (Qwindow_scroll_functions, "window-scroll-functions");
 36771   DEFSYM (Qinhibit_point_motion_hooks, "inhibit-point-motion-hooks");
 36772   DEFSYM (Qeval, "eval");
 36773   DEFSYM (QCdata, ":data");
 36774 
 36775   /* Names of text properties relevant for redisplay.  */
 36776   DEFSYM (Qdisplay, "display");
 36777   DEFSYM (Qspace_width, "space-width");
 36778   DEFSYM (Qraise, "raise");
 36779   DEFSYM (Qslice, "slice");
 36780   DEFSYM (Qspace, "space");
 36781   DEFSYM (Qmargin, "margin");
 36782   DEFSYM (Qpointer, "pointer");
 36783   DEFSYM (Qleft_margin, "left-margin");
 36784   DEFSYM (Qright_margin, "right-margin");
 36785   DEFSYM (Qcenter, "center");
 36786   DEFSYM (Qline_height, "line-height");
 36787   DEFSYM (QCalign_to, ":align-to");
 36788   DEFSYM (QCrelative_width, ":relative-width");
 36789   DEFSYM (QCrelative_height, ":relative-height");
 36790   DEFSYM (QCeval, ":eval");
 36791   DEFSYM (QCpropertize, ":propertize");
 36792   DEFSYM (QCfile, ":file");
 36793   DEFSYM (Qfontified, "fontified");
 36794   DEFSYM (Qfontification_functions, "fontification-functions");
 36795   DEFSYM (Qlong_line_optimizations_in_fontification_functions,
 36796           "long-line-optimizations-in-fontification-functions");
 36797 
 36798   /* Name of the symbol which disables Lisp evaluation in 'display'
 36799      properties.  This is used by enriched.el.  */
 36800   DEFSYM (Qdisable_eval, "disable-eval");
 36801 
 36802   /* Name of the face used to highlight trailing whitespace.  */
 36803   DEFSYM (Qtrailing_whitespace, "trailing-whitespace");
 36804 
 36805   /* Names of the faces used to display line numbers.  */
 36806   DEFSYM (Qline_number, "line-number");
 36807   DEFSYM (Qline_number_current_line, "line-number-current-line");
 36808   DEFSYM (Qline_number_major_tick, "line-number-major-tick");
 36809   DEFSYM (Qline_number_minor_tick, "line-number-minor-tick");
 36810   /* Name of a text property which disables line-number display.  */
 36811   DEFSYM (Qdisplay_line_numbers_disable, "display-line-numbers-disable");
 36812 
 36813   /* Name of the face used to display fill column indicator character.  */
 36814   DEFSYM (Qfill_column_indicator, "fill-column-indicator");
 36815 
 36816   /* Name and number of the face used to highlight escape glyphs.  */
 36817   DEFSYM (Qescape_glyph, "escape-glyph");
 36818 
 36819   /* Name and number of the face used to highlight non-breaking
 36820      spaces/hyphens.  */
 36821   DEFSYM (Qnobreak_space, "nobreak-space");
 36822   DEFSYM (Qnobreak_hyphen, "nobreak-hyphen");
 36823 
 36824   /* The symbol 'image' which is the car of the lists used to represent
 36825      images in Lisp.  Also a tool bar style.  */
 36826   DEFSYM (Qimage, "image");
 36827 
 36828   /* Tool bar styles.  */
 36829   DEFSYM (Qtext, "text");
 36830   DEFSYM (Qboth, "both");
 36831   DEFSYM (Qboth_horiz, "both-horiz");
 36832   DEFSYM (Qtext_image_horiz, "text-image-horiz");
 36833 
 36834   /* The image map types.  */
 36835   DEFSYM (QCmap, ":map");
 36836   DEFSYM (QCpointer, ":pointer");
 36837   DEFSYM (Qrect, "rect");
 36838   DEFSYM (Qcircle, "circle");
 36839   DEFSYM (Qpoly, "poly");
 36840 
 36841   DEFSYM (Qinhibit_menubar_update, "inhibit-menubar-update");
 36842 
 36843   DEFSYM (Qgrow_only, "grow-only");
 36844   DEFSYM (Qinhibit_eval_during_redisplay, "inhibit-eval-during-redisplay");
 36845   DEFSYM (Qposition, "position");
 36846   DEFSYM (Qbuffer_position, "buffer-position");
 36847   DEFSYM (Qobject, "object");
 36848 
 36849   /* Cursor shapes.  */
 36850   DEFSYM (Qbar, "bar");
 36851   DEFSYM (Qhbar, "hbar");
 36852   DEFSYM (Qbox, "box");
 36853   DEFSYM (Qhollow, "hollow");
 36854 
 36855   /* Pointer shapes.  */
 36856   DEFSYM (Qhand, "hand");
 36857   DEFSYM (Qarrow, "arrow");
 36858   /* also Qtext */
 36859 
 36860   DEFSYM (Qdragging, "dragging");
 36861   DEFSYM (Qdropping, "dropping");
 36862   DEFSYM (Qdrag_source, "drag-source");
 36863 
 36864   DEFSYM (Qdrag_with_mode_line, "drag-with-mode-line");
 36865   DEFSYM (Qdrag_with_header_line, "drag-with-header-line");
 36866   DEFSYM (Qdrag_with_tab_line, "drag-with-tab-line");
 36867 
 36868   DEFSYM (Qinhibit_free_realized_faces, "inhibit-free-realized-faces");
 36869 
 36870   list_of_error = list1 (Qerror);
 36871   staticpro (&list_of_error);
 36872 
 36873   /* Values of those variables at last redisplay are stored as
 36874      properties on 'overlay-arrow-position' symbol.  However, if
 36875      Voverlay_arrow_position is a marker, last-arrow-position is its
 36876      numerical position.  */
 36877   DEFSYM (Qlast_arrow_position, "last-arrow-position");
 36878   DEFSYM (Qlast_arrow_string, "last-arrow-string");
 36879 
 36880   /* Alternative overlay-arrow-string and overlay-arrow-bitmap
 36881      properties on a symbol in overlay-arrow-variable-list.  */
 36882   DEFSYM (Qoverlay_arrow_string, "overlay-arrow-string");
 36883   DEFSYM (Qoverlay_arrow_bitmap, "overlay-arrow-bitmap");
 36884 
 36885   echo_buffer[0] = echo_buffer[1] = Qnil;
 36886   staticpro (&echo_buffer[0]);
 36887   staticpro (&echo_buffer[1]);
 36888 
 36889   echo_area_buffer[0] = echo_area_buffer[1] = Qnil;
 36890   staticpro (&echo_area_buffer[0]);
 36891   staticpro (&echo_area_buffer[1]);
 36892 
 36893   DEFVAR_LISP ("messages-buffer-name", Vmessages_buffer_name,
 36894     doc: /* The name of the buffer where messages are logged.
 36895 This is normally \"\*Messages*\", but can be rebound by packages that
 36896 wish to redirect messages to a different buffer.  (If the buffer
 36897 doesn't exist, it will be created and put into
 36898 `messages-buffer-mode'.)  */);
 36899   Vmessages_buffer_name = build_string ("*Messages*");
 36900 
 36901   mode_line_proptrans_alist = Qnil;
 36902   staticpro (&mode_line_proptrans_alist);
 36903   mode_line_string_list = Qnil;
 36904   staticpro (&mode_line_string_list);
 36905   mode_line_string_face = Qnil;
 36906   staticpro (&mode_line_string_face);
 36907   mode_line_string_face_prop = Qnil;
 36908   staticpro (&mode_line_string_face_prop);
 36909   Vmode_line_unwind_vector = Qnil;
 36910   staticpro (&Vmode_line_unwind_vector);
 36911 
 36912   DEFSYM (Qmode_line_default_help_echo, "mode-line-default-help-echo");
 36913 
 36914   help_echo_string = Qnil;
 36915   staticpro (&help_echo_string);
 36916   help_echo_object = Qnil;
 36917   staticpro (&help_echo_object);
 36918   help_echo_window = Qnil;
 36919   staticpro (&help_echo_window);
 36920   previous_help_echo_string = Qnil;
 36921   staticpro (&previous_help_echo_string);
 36922   help_echo_pos = -1;
 36923 
 36924   DEFSYM (Qright_to_left, "right-to-left");
 36925   DEFSYM (Qleft_to_right, "left-to-right");
 36926   defsubr (&Sbidi_resolved_levels);
 36927 
 36928 #ifdef HAVE_WINDOW_SYSTEM
 36929   DEFVAR_BOOL ("x-stretch-cursor", x_stretch_cursor_p,
 36930     doc: /* Non-nil means draw block cursor as wide as the glyph under it.
 36931 For example, if a block cursor is over a tab, it will be drawn as
 36932 wide as that tab on the display.  */);
 36933   x_stretch_cursor_p = 0;
 36934 #endif
 36935 
 36936   DEFVAR_LISP ("show-trailing-whitespace", Vshow_trailing_whitespace,
 36937     doc: /* Non-nil means highlight trailing whitespace.
 36938 The face used for trailing whitespace is `trailing-whitespace'.  */);
 36939   Vshow_trailing_whitespace = Qnil;
 36940 
 36941   DEFVAR_LISP ("mode-line-compact", Vmode_line_compact,
 36942     doc: /* Non-nil means that mode lines should be compact.
 36943 This means that repeating spaces will be replaced with a single space.
 36944 If this variable is `long', only mode lines that are wider than the
 36945 currently selected window are compressed. */);
 36946   Vmode_line_compact = Qnil;
 36947   DEFSYM (Qlong, "long");
 36948 
 36949   DEFVAR_LISP ("nobreak-char-display", Vnobreak_char_display,
 36950     doc: /* Control highlighting of non-ASCII space and hyphen chars.
 36951 If the value is t, Emacs highlights non-ASCII chars which have the
 36952 same appearance as an ASCII space or hyphen, using the `nobreak-space'
 36953 or `nobreak-hyphen' face respectively.
 36954 
 36955 All of the non-ASCII characters in the Unicode horizontal whitespace
 36956 character class, as well as U+00AD (soft hyphen), U+2010 (hyphen), and
 36957 U+2011 (non-breaking hyphen) are affected.
 36958 
 36959 Any other non-nil value means to display these characters as an escape
 36960 glyph followed by an ordinary space or hyphen.
 36961 
 36962 A value of nil means no special handling of these characters.  */);
 36963   Vnobreak_char_display = Qt;
 36964 
 36965   DEFVAR_BOOL ("nobreak-char-ascii-display", nobreak_char_ascii_display,
 36966     doc: /* Control display of non-ASCII space and hyphen chars.
 36967 If the value of this variable is nil, the default, Emacs displays
 36968 non-ASCII chars which have the same appearance as an ASCII space
 36969 or hyphen as themselves, with the `nobreak-space' or `nobreak-hyphen'
 36970 face, respectively.
 36971 
 36972 If the value is t, these characters are displayed as their ASCII
 36973 counterparts: whitespace characters as ASCII space, hyphen characters
 36974 as ASCII hyphen (a.k.a. \"dash\"), using the `nobreak-space' or
 36975 the `nobreak-hyphen' face.
 36976 
 36977 This variable has effect only if `nobreak-char-display' is t;
 36978 otherwise it is ignored.
 36979 
 36980 All of the non-ASCII characters in the Unicode horizontal whitespace
 36981 character class, as well as U+00AD (soft hyphen), U+2010 (hyphen), and
 36982 U+2011 (non-breaking hyphen) are affected.  */);
 36983   nobreak_char_ascii_display = false;
 36984 
 36985   DEFVAR_LISP ("void-text-area-pointer", Vvoid_text_area_pointer,
 36986     doc: /* The pointer shape to show in void text areas.
 36987 A value of nil means to show the text pointer.  Other options are
 36988 `arrow', `text', `hand', `vdrag', `hdrag', `nhdrag', `modeline', and
 36989 `hourglass'.  */);
 36990   Vvoid_text_area_pointer = Qarrow;
 36991 
 36992   DEFVAR_LISP ("inhibit-redisplay", Vinhibit_redisplay,
 36993     doc: /* Non-nil means don't actually do any redisplay.
 36994 This is used for internal purposes.  */);
 36995   Vinhibit_redisplay = Qnil;
 36996 
 36997   DEFVAR_LISP ("global-mode-string", Vglobal_mode_string,
 36998     doc: /* String (or mode line construct) included (normally) in `mode-line-misc-info'.  */);
 36999   Vglobal_mode_string = Qnil;
 37000 
 37001   DEFVAR_LISP ("overlay-arrow-position", Voverlay_arrow_position,
 37002     doc: /* Marker for where to display an arrow on top of the buffer text.
 37003 This must be the beginning of a line in order to work.
 37004 See also `overlay-arrow-string'.  */);
 37005   Voverlay_arrow_position = Qnil;
 37006 
 37007   DEFVAR_LISP ("overlay-arrow-string", Voverlay_arrow_string,
 37008     doc: /* String to display as an arrow in non-window frames.
 37009 See also `overlay-arrow-position'.  */);
 37010   Voverlay_arrow_string = build_pure_c_string ("=>");
 37011 
 37012   DEFVAR_LISP ("overlay-arrow-variable-list", Voverlay_arrow_variable_list,
 37013     doc: /* List of variables (symbols) which hold markers for overlay arrows.
 37014 The symbols on this list are examined during redisplay to determine
 37015 where to display overlay arrows.  */);
 37016   Voverlay_arrow_variable_list
 37017     = list1 (intern_c_string ("overlay-arrow-position"));
 37018 
 37019   DEFVAR_INT ("scroll-step", emacs_scroll_step,
 37020     doc: /* The number of lines to try scrolling a window by when point moves out.
 37021 If that fails to bring point back on frame, point is centered instead.
 37022 If this is zero, point is always centered after it moves off frame.
 37023 If you want scrolling to always be a line at a time, you should set
 37024 `scroll-conservatively' to a large value rather than set this to 1.  */);
 37025 
 37026   DEFVAR_INT ("scroll-conservatively", scroll_conservatively,
 37027     doc: /* Scroll up to this many lines, to bring point back on screen.
 37028 If point moves off-screen, redisplay will scroll by up to
 37029 `scroll-conservatively' lines in order to bring point just barely
 37030 onto the screen again.  If that cannot be done, then redisplay
 37031 recenters point as usual.
 37032 
 37033 If the value is greater than 100, redisplay will never recenter point,
 37034 but will always scroll just enough text to bring point into view, even
 37035 if you move far away.
 37036 
 37037 A value of zero means always recenter point if it moves off screen.  */);
 37038   scroll_conservatively = 0;
 37039 
 37040   DEFVAR_INT ("scroll-margin", scroll_margin,
 37041     doc: /* Number of lines of margin at the top and bottom of a window.
 37042 Trigger automatic scrolling whenever point gets within this many lines
 37043 of the top or bottom of the window (see info node `Auto Scrolling').  */);
 37044   scroll_margin = 0;
 37045 
 37046   DEFVAR_LISP ("maximum-scroll-margin", Vmaximum_scroll_margin,
 37047     doc: /* Maximum effective value of `scroll-margin'.
 37048 Given as a fraction of the current window's lines.  The value should
 37049 be a floating point number between 0.0 and 0.5.  The effective maximum
 37050 is limited to (/ (1- window-lines) 2).  Non-float values for this
 37051 variable are ignored and the default 0.25 is used instead.  */);
 37052   Vmaximum_scroll_margin = make_float (0.25);
 37053 
 37054   DEFVAR_LISP ("display-pixels-per-inch",  Vdisplay_pixels_per_inch,
 37055     doc: /* Pixels per inch value for non-window system displays.
 37056 Value is a number or a cons (WIDTH-DPI . HEIGHT-DPI).  */);
 37057   Vdisplay_pixels_per_inch = make_float (72.0);
 37058 
 37059 #ifdef GLYPH_DEBUG
 37060   DEFVAR_INT ("debug-end-pos", debug_end_pos, doc: /* Don't ask.  */);
 37061 #endif
 37062 
 37063   DEFVAR_LISP ("truncate-partial-width-windows",
 37064                Vtruncate_partial_width_windows,
 37065     doc: /* Non-nil means truncate lines in windows narrower than the frame.
 37066 For an integer value, truncate lines in each window narrower than the
 37067 full frame width, provided the total window width in column units is less
 37068 than that integer; otherwise, respect the value of `truncate-lines'.
 37069 The total width of the window is as returned by `window-total-width', it
 37070 includes the fringes, the continuation and truncation glyphs, the
 37071 display margins (if any), and the scroll bar
 37072 
 37073 For any other non-nil value, truncate lines in all windows that do
 37074 not span the full frame width.
 37075 
 37076 A value of nil means to respect the value of `truncate-lines'.
 37077 
 37078 If `word-wrap' is enabled, you might want to reduce the value of this.
 37079 
 37080 Don't set this to a non-nil value when `visual-line-mode' is
 37081 turned on, as it could produce confusing results.  */);
 37082   Vtruncate_partial_width_windows = make_fixnum (50);
 37083 
 37084   DEFVAR_BOOL("word-wrap-by-category", word_wrap_by_category, doc: /*
 37085     Non-nil means also wrap after characters of a certain category.
 37086 Normally when `word-wrap' is on, Emacs only breaks lines after
 37087 whitespace characters.  When this option is turned on, Emacs also
 37088 breaks lines after characters that have the "|" category (defined in
 37089 characters.el).  This is useful for allowing breaking after CJK
 37090 characters and improves the word-wrapping for CJK text mixed with
 37091 Latin text.
 37092 
 37093 If this variable is set using Customize, Emacs automatically loads
 37094 kinsoku.el.  When kinsoku.el is loaded, Emacs respects kinsoku rules
 37095 when breaking lines.  That means characters with the ">" category
 37096 don't appear at the beginning of a line (e.g., FULLWIDTH COMMA), and
 37097 characters with the "<" category don't appear at the end of a line
 37098 (e.g., LEFT DOUBLE ANGLE BRACKET).  */);
 37099   word_wrap_by_category = false;
 37100 
 37101   DEFVAR_LISP ("line-number-display-limit", Vline_number_display_limit,
 37102     doc: /* Maximum buffer size for which line number should be displayed.
 37103 If the buffer is bigger than this, the line number does not appear
 37104 in the mode line.  A value of nil means no limit.  */);
 37105   Vline_number_display_limit = Qnil;
 37106 
 37107   DEFVAR_INT ("line-number-display-limit-width",
 37108               line_number_display_limit_width,
 37109     doc: /* Maximum line width (in characters) for line number display.
 37110 If the average length of the lines near point is bigger than this, then the
 37111 line number may be omitted from the mode line.  */);
 37112   line_number_display_limit_width = 200;
 37113 
 37114   DEFVAR_BOOL ("highlight-nonselected-windows", highlight_nonselected_windows,
 37115     doc: /* Non-nil means highlight active region even in nonselected windows.
 37116 When nil (the default), the active region is only highlighted when
 37117 the window is selected.  */);
 37118   highlight_nonselected_windows = false;
 37119 
 37120   DEFVAR_BOOL ("multiple-frames", multiple_frames,
 37121     doc: /* Non-nil if more than one frame is visible on this display.
 37122 Minibuffer-only frames don't count, but iconified frames do.
 37123 This variable is not guaranteed to be accurate except while processing
 37124 `frame-title-format' and `icon-title-format'.  */);
 37125 
 37126   DEFVAR_LISP ("frame-title-format", Vframe_title_format,
 37127     doc: /* Template for displaying the title bar of visible frames.
 37128 \(Assuming the window manager supports this feature.)
 37129 
 37130 This variable has the same structure as `mode-line-format', except that
 37131 the %c, %C, and %l constructs are ignored.  It is used only on frames for
 37132 which no explicit name has been set (see `modify-frame-parameters').  */);
 37133 
 37134   DEFVAR_LISP ("icon-title-format", Vicon_title_format,
 37135     doc: /* Template for displaying the title bar of an iconified frame.
 37136 \(Assuming the window manager supports this feature.)
 37137 If the value is a string, it should have the same structure
 37138 as `mode-line-format' (which see), and is used only on frames
 37139 for which no explicit name has been set \(see `modify-frame-parameters').
 37140 If the value is t, that means use `frame-title-format' for
 37141 iconified frames.  */);
 37142   /* Do not nest calls to pure_list.  This works around a bug in
 37143      Oracle Developer Studio 12.6.  */
 37144   Lisp_Object icon_title_name_format
 37145     = pure_list (empty_unibyte_string,
 37146                  build_pure_c_string ("%b - GNU Emacs at "),
 37147                  intern_c_string ("system-name"));
 37148   Vicon_title_format
 37149     = Vframe_title_format
 37150     = pure_list (intern_c_string ("multiple-frames"),
 37151                  build_pure_c_string ("%b"),
 37152                  icon_title_name_format);
 37153 
 37154   DEFVAR_LISP ("message-log-max", Vmessage_log_max,
 37155     doc: /* Maximum number of lines to keep in the message log buffer.
 37156 If nil, disable message logging.  If t, log messages but don't truncate
 37157 the buffer when it becomes large.  */);
 37158   Vmessage_log_max = make_fixnum (1000);
 37159 
 37160   DEFVAR_LISP ("window-scroll-functions", Vwindow_scroll_functions,
 37161     doc: /* List of functions to call before redisplaying a window with scrolling.
 37162 Each function is called with two arguments, the window and its new
 37163 display-start position.
 37164 These functions are called whenever the `window-start' marker is modified,
 37165 either to point into another buffer (e.g. via `set-window-buffer') or another
 37166 place in the same buffer.
 37167 When each function is called, the `window-start' marker of its window
 37168 argument has been already set to the new value, and the buffer which that
 37169 window will display is set to be the current buffer.
 37170 Note that the value of `window-end' is not valid when these functions are
 37171 called.
 37172 
 37173 Warning: Do not use this feature to alter the way the window
 37174 is scrolled.  It is not designed for that, and such use probably won't
 37175 work.  */);
 37176   Vwindow_scroll_functions = Qnil;
 37177 
 37178   DEFVAR_LISP ("mouse-autoselect-window", Vmouse_autoselect_window,
 37179      doc: /* Non-nil means autoselect window with mouse pointer.
 37180 If nil, do not autoselect windows.
 37181 A positive number means delay autoselection by that many seconds: a
 37182 window is autoselected only after the mouse has remained in that
 37183 window for the duration of the delay.
 37184 A negative number has a similar effect, but causes windows to be
 37185 autoselected only after the mouse has stopped moving.  (Because of
 37186 the way Emacs compares mouse events, you will occasionally wait twice
 37187 that time before the window gets selected.)
 37188 Any other value means to autoselect window instantaneously when the
 37189 mouse pointer enters it.
 37190 
 37191 Autoselection selects the minibuffer only if it is active, and never
 37192 unselects the minibuffer if it is active.
 37193 
 37194 If you want to use the mouse to autoselect a window on another frame,
 37195 make sure that (1) your window manager has focus follow the mouse and
 37196 (2) the value of the option `focus-follows-mouse' matches the policy
 37197 of your window manager.  */);
 37198   Vmouse_autoselect_window = Qnil;
 37199 
 37200   DEFVAR_LISP ("auto-resize-tab-bars", Vauto_resize_tab_bars,
 37201     doc: /* Non-nil means automatically resize tab-bars.
 37202 This dynamically changes the tab-bar's height to the minimum height
 37203 that is needed to make all tab-bar items visible.
 37204 If value is `grow-only', the tab-bar's height is only increased
 37205 automatically; to decrease the tab-bar height, use \\[recenter],
 37206 after setting `recenter-redisplay' to the value of t.  */);
 37207   Vauto_resize_tab_bars = Qt;
 37208 
 37209   DEFVAR_BOOL ("auto-raise-tab-bar-buttons", auto_raise_tab_bar_buttons_p,
 37210     doc: /* Non-nil means raise tab-bar buttons when the mouse moves over them.  */);
 37211   auto_raise_tab_bar_buttons_p = true;
 37212 
 37213   DEFVAR_LISP ("auto-resize-tool-bars", Vauto_resize_tool_bars,
 37214     doc: /* Non-nil means automatically resize tool-bars.
 37215 This dynamically changes the tool-bar's height to the minimum height
 37216 that is needed to make all tool-bar items visible.
 37217 If value is `grow-only', the tool-bar's height is only increased
 37218 automatically; to decrease the tool-bar height, use \\[recenter],
 37219 after setting `recenter-redisplay' to the value of t.  */);
 37220   Vauto_resize_tool_bars = Qt;
 37221 
 37222   DEFVAR_BOOL ("auto-raise-tool-bar-buttons", auto_raise_tool_bar_buttons_p,
 37223     doc: /* Non-nil means raise tool-bar buttons when the mouse moves over them.  */);
 37224   auto_raise_tool_bar_buttons_p = true;
 37225 
 37226   DEFVAR_LISP ("make-cursor-line-fully-visible", Vmake_cursor_line_fully_visible,
 37227     doc: /* Whether to scroll the window if the cursor line is not fully visible.
 37228 If the value is non-nil, Emacs scrolls or recenters the window to make
 37229 the cursor line fully visible.  The value could also be a function, which
 37230 is called with a single argument, the window to be scrolled, and should
 37231 return non-nil if the partially-visible cursor requires scrolling the
 37232 window, nil if it's okay to leave the cursor partially-visible.  */);
 37233   Vmake_cursor_line_fully_visible = Qt;
 37234   DEFSYM (Qmake_cursor_line_fully_visible, "make-cursor-line-fully-visible");
 37235 
 37236   DEFVAR_BOOL ("make-window-start-visible", make_window_start_visible,
 37237     doc: /* Whether to ensure `window-start' position is never invisible.  */);
 37238   make_window_start_visible = false;
 37239   DEFSYM (Qmake_window_start_visible, "make-window-start-visible");
 37240   Fmake_variable_buffer_local (Qmake_window_start_visible);
 37241 
 37242   DEFSYM (Qclose_tab, "close-tab");
 37243   DEFVAR_LISP ("tab-bar-border", Vtab_bar_border,
 37244     doc: /* Border below tab-bar in pixels.
 37245 If an integer, use it as the height of the border.
 37246 If it is one of `internal-border-width' or `border-width', use the
 37247 value of the corresponding frame parameter.
 37248 Otherwise, no border is added below the tab-bar.  */);
 37249   Vtab_bar_border = Qinternal_border_width;
 37250 
 37251   DEFVAR_LISP ("tab-bar-button-margin", Vtab_bar_button_margin,
 37252     doc: /* Margin around tab-bar buttons in pixels.
 37253 If an integer, use that for both horizontal and vertical margins.
 37254 Otherwise, value should be a pair of integers `(HORZ . VERT)' with
 37255 HORZ specifying the horizontal margin, and VERT specifying the
 37256 vertical margin.  */);
 37257   Vtab_bar_button_margin = make_fixnum (DEFAULT_TAB_BAR_BUTTON_MARGIN);
 37258 
 37259   DEFVAR_INT ("tab-bar-button-relief", tab_bar_button_relief,
 37260     doc: /* Relief thickness of tab-bar buttons.  */);
 37261   tab_bar_button_relief = DEFAULT_TAB_BAR_BUTTON_RELIEF;
 37262 
 37263   DEFVAR_LISP ("tool-bar-border", Vtool_bar_border,
 37264     doc: /* Border below tool-bar in pixels.
 37265 If an integer, use it as the height of the border.
 37266 If it is one of `internal-border-width' or `border-width', use the
 37267 value of the corresponding frame parameter.
 37268 Otherwise, no border is added below the tool-bar.  */);
 37269   Vtool_bar_border = Qinternal_border_width;
 37270 
 37271   DEFVAR_LISP ("tool-bar-button-margin", Vtool_bar_button_margin,
 37272     doc: /* Margin around tool-bar buttons in pixels.
 37273 If an integer, use that for both horizontal and vertical margins.
 37274 Otherwise, value should be a pair of integers `(HORZ . VERT)' with
 37275 HORZ specifying the horizontal margin, and VERT specifying the
 37276 vertical margin.  */);
 37277   Vtool_bar_button_margin = make_fixnum (DEFAULT_TOOL_BAR_BUTTON_MARGIN);
 37278 
 37279   DEFVAR_INT ("tool-bar-button-relief", tool_bar_button_relief,
 37280     doc: /* Relief thickness of tool-bar buttons.  */);
 37281   tool_bar_button_relief = DEFAULT_TOOL_BAR_BUTTON_RELIEF;
 37282 
 37283   DEFVAR_LISP ("tool-bar-style", Vtool_bar_style,
 37284     doc: /* Tool bar style to use.
 37285 It can be one of
 37286  image            - show images only
 37287  text             - show text only
 37288  both             - show both, text below image
 37289  both-horiz       - show text to the right of the image
 37290  text-image-horiz - show text to the left of the image
 37291  any other        - use system default or image if no system default.
 37292 
 37293 This variable only affects the GTK+ toolkit version of Emacs.  */);
 37294   Vtool_bar_style = Qnil;
 37295 
 37296   DEFVAR_INT ("tool-bar-max-label-size", tool_bar_max_label_size,
 37297     doc: /* Maximum number of characters a label can have to be shown.
 37298 The tool bar style must also show labels for this to have any effect, see
 37299 `tool-bar-style'.  */);
 37300   tool_bar_max_label_size = DEFAULT_TOOL_BAR_LABEL_SIZE;
 37301 
 37302   DEFVAR_LISP ("fontification-functions", Vfontification_functions,
 37303     doc: /* List of functions to call to fontify regions of text.
 37304 Each function is called with one argument POS.  Functions must
 37305 fontify a region starting at POS in the current buffer, and give
 37306 fontified regions the property `fontified' with a non-nil value.
 37307 
 37308 Note that, when `long-line-optimizations-p' is non-nil in the buffer,
 37309 these functions are called as if they were in a `with-restriction' form,
 37310 with a `long-line-optimizations-in-fontification-functions' label and
 37311 with the buffer narrowed to a portion around POS whose size is
 37312 specified by `long-line-optimizations-region-size'.  */);
 37313   Vfontification_functions = Qnil;
 37314   Fmake_variable_buffer_local (Qfontification_functions);
 37315 
 37316   DEFVAR_BOOL ("unibyte-display-via-language-environment",
 37317                unibyte_display_via_language_environment,
 37318     doc: /* Non-nil means display unibyte text according to language environment.
 37319 Specifically, this means that raw bytes in the range 160-255 decimal
 37320 are displayed by converting them to the equivalent multibyte characters
 37321 according to the current language environment.  As a result, they are
 37322 displayed according to the current fontset.
 37323 
 37324 Note that this variable affects only how these bytes are displayed,
 37325 but does not change the fact they are interpreted as raw bytes.  */);
 37326   unibyte_display_via_language_environment = false;
 37327 
 37328   DEFVAR_LISP ("max-mini-window-height", Vmax_mini_window_height,
 37329     doc: /* Maximum height for resizing mini-windows (the minibuffer and the echo area).
 37330 If a float, it specifies the maximum height in units of the
 37331 mini-window frame's height.
 37332 If an integer, it specifies the maximum height in units of the
 37333 mini-window frame's default font's height.  */);
 37334   Vmax_mini_window_height = make_float (0.25);
 37335 
 37336   DEFVAR_LISP ("resize-mini-windows", Vresize_mini_windows,
 37337     doc: /* How to resize mini-windows (the minibuffer and the echo area).
 37338 A value of nil means don't automatically resize mini-windows.
 37339 A value of t means resize them to fit the text displayed in them.
 37340 A value of `grow-only', the default, means let mini-windows grow only;
 37341 they return to their normal size when the minibuffer is closed, or the
 37342 echo area becomes empty.
 37343 
 37344 This variable does not affect resizing of the minibuffer window of
 37345 minibuffer-only frames.  These are handled by `resize-mini-frames'
 37346 only.  */);
 37347   /* Contrary to the doc string, we initialize this to nil, so that
 37348      loading loadup.el won't try to resize windows before loading
 37349      window.el, where some functions we need to call for this live.
 37350      We assign the 'grow-only' value right after loading window.el
 37351      during loadup.  */
 37352   Vresize_mini_windows = Qnil;
 37353 
 37354   DEFVAR_LISP ("blink-cursor-alist", Vblink_cursor_alist,
 37355     doc: /* Alist specifying how to blink the cursor off.
 37356 Each element has the form (ON-STATE . OFF-STATE).  Whenever the
 37357 `cursor-type' frame-parameter or variable equals ON-STATE,
 37358 comparing using `equal', Emacs uses OFF-STATE to specify
 37359 how to blink it off.  ON-STATE and OFF-STATE are values for
 37360 the `cursor-type' frame parameter.
 37361 
 37362 If a frame's ON-STATE has no entry in this list,
 37363 the frame's other specifications determine how to blink the cursor off.  */);
 37364   Vblink_cursor_alist = Qnil;
 37365 
 37366   DEFVAR_LISP ("auto-hscroll-mode", automatic_hscrolling,
 37367     doc: /* Allow or disallow automatic horizontal scrolling of windows.
 37368 The value `current-line' means the line displaying point in each window
 37369 is automatically scrolled horizontally to make point visible.
 37370 Any other non-nil value means all the lines in a window are automatically
 37371 scrolled horizontally to make point visible.  */);
 37372   automatic_hscrolling = Qt;
 37373   DEFSYM (Qauto_hscroll_mode, "auto-hscroll-mode");
 37374   DEFSYM (Qcurrent_line, "current-line");
 37375 
 37376   DEFVAR_INT ("hscroll-margin", hscroll_margin,
 37377     doc: /* How many columns away from the window edge point is allowed to get
 37378 before automatic hscrolling will horizontally scroll the window.  */);
 37379   hscroll_margin = 5;
 37380 
 37381   DEFVAR_LISP ("hscroll-step", Vhscroll_step,
 37382     doc: /* How many columns to scroll the window when point gets too close to the edge.
 37383 When point is less than `hscroll-margin' columns from the window
 37384 edge, automatic hscrolling will scroll the window by the amount of columns
 37385 determined by this variable.  If its value is a positive integer, scroll that
 37386 many columns.  If it's a positive floating-point number, it specifies the
 37387 fraction of the window's width to scroll.  If it's nil or zero, point will be
 37388 centered horizontally after the scroll.  Any other value, including negative
 37389 numbers, are treated as if the value were zero.
 37390 
 37391 Automatic hscrolling always moves point outside the scroll margin, so if
 37392 point was more than scroll step columns inside the margin, the window will
 37393 scroll more than the value given by the scroll step.
 37394 
 37395 Note that the lower bound for automatic hscrolling specified by `scroll-left'
 37396 and `scroll-right' overrides this variable's effect.  */);
 37397   Vhscroll_step = make_fixnum (0);
 37398 
 37399   DEFVAR_BOOL ("message-truncate-lines", message_truncate_lines,
 37400     doc: /* If non-nil, messages are truncated when displaying the echo area.
 37401 Bind this around calls to `message' to let it take effect.  */);
 37402   message_truncate_lines = false;
 37403 
 37404   DEFVAR_LISP ("menu-bar-update-hook",  Vmenu_bar_update_hook,
 37405     doc: /* Normal hook run to update the menu bar definitions.
 37406 Redisplay runs this hook before it redisplays the menu bar.
 37407 This is used to update menus such as Buffers, whose contents depend on
 37408 various data.  */);
 37409   Vmenu_bar_update_hook = Qnil;
 37410 
 37411   DEFVAR_LISP ("menu-updating-frame", Vmenu_updating_frame,
 37412                doc: /* Frame for which we are updating a menu.
 37413 The enable predicate for a menu binding should check this variable.  */);
 37414   Vmenu_updating_frame = Qnil;
 37415 
 37416   DEFVAR_BOOL ("inhibit-menubar-update", inhibit_menubar_update,
 37417     doc: /* Non-nil means don't update menu bars.  Internal use only.  */);
 37418   inhibit_menubar_update = false;
 37419 
 37420   DEFVAR_LISP ("wrap-prefix", Vwrap_prefix,
 37421     doc: /* Prefix prepended to all continuation lines at display time.
 37422 The value may be a string, an image, or a stretch-glyph; it is
 37423 interpreted in the same way as the value of a `display' text property.
 37424 
 37425 This variable is overridden by any `wrap-prefix' text or overlay
 37426 property.
 37427 
 37428 To add a prefix to non-continuation lines, use `line-prefix'.  */);
 37429   Vwrap_prefix = Qnil;
 37430   DEFSYM (Qwrap_prefix, "wrap-prefix");
 37431   Fmake_variable_buffer_local (Qwrap_prefix);
 37432 
 37433   DEFVAR_LISP ("line-prefix", Vline_prefix,
 37434     doc: /* Prefix prepended to all non-continuation lines at display time.
 37435 The value may be a string, an image, or a stretch-glyph; it is
 37436 interpreted in the same way as the value of a `display' text property.
 37437 
 37438 This variable is overridden by any `line-prefix' text or overlay
 37439 property.
 37440 
 37441 To add a prefix to continuation lines, use `wrap-prefix'.  */);
 37442   Vline_prefix = Qnil;
 37443   DEFSYM (Qline_prefix, "line-prefix");
 37444   Fmake_variable_buffer_local (Qline_prefix);
 37445 
 37446   DEFVAR_LISP ("display-line-numbers", Vdisplay_line_numbers,
 37447     doc: /* Non-nil means display line numbers.
 37448 
 37449 If the value is t, display the absolute number of each line of a buffer
 37450 shown in a window.  Absolute line numbers count from the beginning of
 37451 the current narrowing, or from buffer beginning.  The variable
 37452 `display-line-numbers-offset', if non-zero, is a signed offset added
 37453 to each absolute line number; it also forces line numbers to be counted
 37454 from the beginning of the buffer, as if `display-line-numbers-widen'
 37455 were non-nil.  It has no effect when line numbers are not absolute.
 37456 
 37457 If the value is `relative', display for each line not containing the
 37458 window's point its relative number instead, i.e. the number of the line
 37459 relative to the line showing the window's point.
 37460 
 37461 In either case, line numbers are displayed at the beginning of each
 37462 non-continuation line that displays buffer text, i.e. after each newline
 37463 character that comes from the buffer.  The value `visual' is like
 37464 `relative' but counts screen lines instead of buffer lines.  In practice
 37465 this means that continuation lines count as well when calculating the
 37466 relative number of a line.
 37467 
 37468 Lisp programs can disable display of a line number of a particular
 37469 buffer line by putting the `display-line-numbers-disable' text property
 37470 or overlay property on the first visible character of that line.  */);
 37471   Vdisplay_line_numbers = Qnil;
 37472   DEFSYM (Qdisplay_line_numbers, "display-line-numbers");
 37473   Fmake_variable_buffer_local (Qdisplay_line_numbers);
 37474   DEFSYM (Qrelative, "relative");
 37475   DEFSYM (Qvisual, "visual");
 37476 
 37477   DEFVAR_LISP ("display-line-numbers-width", Vdisplay_line_numbers_width,
 37478     doc: /* Minimum width of space reserved for line number display.
 37479 A positive number means reserve that many columns for line numbers,
 37480 even if the actual number needs less space.
 37481 The default value of nil means compute the space dynamically.
 37482 Any other value is treated as nil.  */);
 37483   Vdisplay_line_numbers_width = Qnil;
 37484   DEFSYM (Qdisplay_line_numbers_width, "display-line-numbers-width");
 37485   Fmake_variable_buffer_local (Qdisplay_line_numbers_width);
 37486 
 37487   DEFVAR_LISP ("display-line-numbers-current-absolute",
 37488                Vdisplay_line_numbers_current_absolute,
 37489     doc: /* Non-nil means display absolute number of current line.
 37490 This variable has effect only when `display-line-numbers' is
 37491 either `relative' or `visual'.  */);
 37492   Vdisplay_line_numbers_current_absolute = Qt;
 37493 
 37494   DEFVAR_BOOL ("display-line-numbers-widen", display_line_numbers_widen,
 37495     doc: /* Non-nil means display line numbers disregarding any narrowing.  */);
 37496   display_line_numbers_widen = false;
 37497   DEFSYM (Qdisplay_line_numbers_widen, "display-line-numbers-widen");
 37498   Fmake_variable_buffer_local (Qdisplay_line_numbers_widen);
 37499 
 37500   DEFVAR_INT ("display-line-numbers-offset", display_line_numbers_offset,
 37501     doc: /* A signed integer added to each absolute line number.
 37502 When this variable is non-zero, line numbers are always counted from
 37503 the beginning of the buffer even if `display-line-numbers-widen' is nil.
 37504 It has no effect when set to 0, or when line numbers are not absolute.  */);
 37505   display_line_numbers_offset = 0;
 37506   DEFSYM (Qdisplay_line_numbers_offset, "display-line-numbers-offset");
 37507   Fmake_variable_buffer_local (Qdisplay_line_numbers_offset);
 37508 
 37509   DEFVAR_BOOL ("display-fill-column-indicator", display_fill_column_indicator,
 37510     doc: /* Non-nil means display the fill column indicator.
 37511 If you set this non-nil, make sure `display-fill-column-indicator-character'
 37512 is also non-nil.
 37513 See Info node `Displaying Boundaries' for details.  */);
 37514   display_fill_column_indicator = false;
 37515   DEFSYM (Qdisplay_fill_column_indicator, "display-fill-column-indicator");
 37516   Fmake_variable_buffer_local (Qdisplay_fill_column_indicator);
 37517 
 37518   DEFVAR_LISP ("display-fill-column-indicator-column", Vdisplay_fill_column_indicator_column,
 37519     doc: /* Column for indicator when `display-fill-column-indicator' is non-nil.
 37520 The default value is t which means that the indicator
 37521 will use the `fill-column' variable.  If it is set to an integer the
 37522 indicator will be drawn in that column.
 37523 See Info node `Displaying Boundaries' for details.  */);
 37524   Vdisplay_fill_column_indicator_column = Qt;
 37525   DEFSYM (Qdisplay_fill_column_indicator_column, "display-fill-column-indicator-column");
 37526   Fmake_variable_buffer_local (Qdisplay_fill_column_indicator_column);
 37527 
 37528   DEFVAR_LISP ("display-fill-column-indicator-character", Vdisplay_fill_column_indicator_character,
 37529     doc: /* Character to draw the indicator when `display-fill-column-indicator' is non-nil.
 37530 A good candidate is U+2502, and an alternative is (ascii 124) if the
 37531 font of `fill-column-indicator' face does not support Unicode characters.
 37532 See Info node `Displaying Boundaries' for details.  */);
 37533   Vdisplay_fill_column_indicator_character = Qnil;
 37534   DEFSYM (Qdisplay_fill_column_indicator_character, "display-fill-column-indicator-character");
 37535   Fmake_variable_buffer_local (Qdisplay_fill_column_indicator_character);
 37536 
 37537   DEFVAR_INT ("display-line-numbers-major-tick", display_line_numbers_major_tick,
 37538     doc: /* If an integer N > 0, highlight line number of every Nth line.
 37539 The line number is shown with the `line-number-major-tick' face.
 37540 Otherwise, no special highlighting is done every Nth line.
 37541 Note that major ticks take precedence over minor ticks.  */);
 37542   display_line_numbers_major_tick = 0;
 37543 
 37544   DEFVAR_INT ("display-line-numbers-minor-tick", display_line_numbers_minor_tick,
 37545     doc: /* If an integer N > 0, highlight line number of every Nth line.
 37546 The line number is shown with the `line-number-minor-tick' face.
 37547 Otherwise, no special highlighting is done every Nth line.
 37548 Note that major ticks take precedence over minor ticks.  */);
 37549   display_line_numbers_minor_tick = 0;
 37550 
 37551   DEFVAR_BOOL ("inhibit-eval-during-redisplay", inhibit_eval_during_redisplay,
 37552     doc: /* Non-nil means don't eval Lisp during redisplay.  */);
 37553   inhibit_eval_during_redisplay = false;
 37554 
 37555   DEFVAR_BOOL ("inhibit-free-realized-faces", inhibit_free_realized_faces,
 37556     doc: /* Non-nil means don't free realized faces.  Internal use only.  */);
 37557   inhibit_free_realized_faces = false;
 37558 
 37559   DEFVAR_BOOL ("inhibit-bidi-mirroring", inhibit_bidi_mirroring,
 37560     doc: /* Non-nil means don't mirror characters even when bidi context requires that.
 37561 Intended for use during debugging and for testing bidi display;
 37562 see biditest.el in the test suite.  */);
 37563   inhibit_bidi_mirroring = false;
 37564 
 37565   DEFVAR_BOOL ("bidi-inhibit-bpa", bidi_inhibit_bpa,
 37566     doc: /* Non-nil means inhibit the Bidirectional Parentheses Algorithm.
 37567 Disabling the BPA makes redisplay faster, but might produce incorrect
 37568 display reordering of bidirectional text with embedded parentheses and
 37569 other bracket characters whose `paired-bracket' Unicode property is
 37570 non-nil, see `get-char-code-property'.  */);
 37571   bidi_inhibit_bpa = false;
 37572 
 37573 #ifdef GLYPH_DEBUG
 37574   DEFVAR_BOOL ("inhibit-try-window-id", inhibit_try_window_id,
 37575                doc: /* Inhibit try_window_id display optimization.  */);
 37576   inhibit_try_window_id = false;
 37577 
 37578   DEFVAR_BOOL ("inhibit-try-window-reusing", inhibit_try_window_reusing,
 37579                doc: /* Inhibit try_window_reusing display optimization.  */);
 37580   inhibit_try_window_reusing = false;
 37581 
 37582   DEFVAR_BOOL ("inhibit-try-cursor-movement", inhibit_try_cursor_movement,
 37583                doc: /* Inhibit try_cursor_movement display optimization.  */);
 37584   inhibit_try_cursor_movement = false;
 37585 #endif /* GLYPH_DEBUG */
 37586 
 37587   DEFVAR_INT ("overline-margin", overline_margin,
 37588                doc: /* Space between overline and text, in pixels.
 37589 The default value is 2: the height of the overline (1 pixel) plus 1 pixel
 37590 margin to the character height.  */);
 37591   overline_margin = 2;
 37592 
 37593   DEFVAR_INT ("underline-minimum-offset",
 37594                underline_minimum_offset,
 37595      doc: /* Minimum distance between baseline and underline.
 37596 This can improve legibility of underlined text at small font sizes,
 37597 particularly when using variable `x-use-underline-position-properties'
 37598 with fonts that specify an UNDERLINE_POSITION relatively close to the
 37599 baseline.  The default value is 1.  */);
 37600   underline_minimum_offset = 1;
 37601   DEFSYM (Qunderline_minimum_offset, "underline-minimum-offset");
 37602 
 37603   DEFVAR_BOOL ("display-hourglass", display_hourglass_p,
 37604                doc: /* Non-nil means show an hourglass pointer, when Emacs is busy.
 37605 This feature only works when on a window system that can change
 37606 cursor shapes.  */);
 37607   display_hourglass_p = true;
 37608 
 37609   DEFVAR_LISP ("hourglass-delay", Vhourglass_delay,
 37610                doc: /* Seconds to wait before displaying an hourglass pointer when Emacs is busy.  */);
 37611   Vhourglass_delay = make_fixnum (DEFAULT_HOURGLASS_DELAY);
 37612 
 37613 #ifdef HAVE_WINDOW_SYSTEM
 37614   hourglass_atimer = NULL;
 37615   hourglass_shown_p = false;
 37616 #endif /* HAVE_WINDOW_SYSTEM */
 37617 
 37618   /* Name of the face used to display glyphless characters.  */
 37619   DEFSYM (Qglyphless_char, "glyphless-char");
 37620 
 37621   /* Method symbols for Vglyphless_char_display.  */
 37622   DEFSYM (Qhex_code, "hex-code");
 37623   DEFSYM (Qempty_box, "empty-box");
 37624   DEFSYM (Qthin_space, "thin-space");
 37625   DEFSYM (Qzero_width, "zero-width");
 37626 
 37627   DEFVAR_LISP ("pre-redisplay-function", Vpre_redisplay_function,
 37628                doc: /* Function run just before redisplay.
 37629 It is called with one argument, which is the set of windows that are to
 37630 be redisplayed.  This set can be nil (meaning, only the selected window),
 37631 or t (meaning all windows).  */);
 37632   Vpre_redisplay_function = intern ("ignore");
 37633 
 37634   /* Symbol for the purpose of Vglyphless_char_display.  */
 37635   DEFSYM (Qglyphless_char_display, "glyphless-char-display");
 37636   Fput (Qglyphless_char_display, Qchar_table_extra_slots, make_fixnum (1));
 37637 
 37638   DEFVAR_LISP ("glyphless-char-display", Vglyphless_char_display,
 37639                doc: /* Char-table defining glyphless characters.
 37640 Each element, if non-nil, should be one of the following:
 37641   an ASCII acronym string: display this string in a box
 37642   `hex-code':   display the hexadecimal code of a character in a box
 37643   `empty-box':  display as an empty box
 37644   `thin-space': display as 1-pixel width space
 37645   `zero-width': don't display
 37646 Any other value is interpreted as `empty-box'.
 37647 An element may also be a cons cell (GRAPHICAL . TEXT), which specifies the
 37648 display method for graphical terminals and text terminals respectively.
 37649 GRAPHICAL and TEXT should each have one of the values listed above.
 37650 
 37651 The char-table has one extra slot to control the display of characters
 37652 for which no font is found on graphical terminals, and characters that
 37653 cannot be displayed by text-mode terminals.  Its value should be an
 37654 ASCII acronym string, `hex-code', `empty-box', or `thin-space'.  It
 37655 could also be a cons cell of any two of these, to specify separate
 37656 values for graphical and text terminals.  The default is `empty-box'.
 37657 
 37658 With the obvious exception of `zero-width', all the other representations
 37659 are displayed using the face `glyphless-char'.
 37660 
 37661 If a character has a non-nil entry in an active display table, the
 37662 display table takes effect; in this case, Emacs does not consult
 37663 `glyphless-char-display' at all.  */);
 37664   Vglyphless_char_display = Fmake_char_table (Qglyphless_char_display, Qnil);
 37665   Fset_char_table_extra_slot (Vglyphless_char_display, make_fixnum (0),
 37666                               Qempty_box);
 37667 
 37668   DEFVAR_LISP ("debug-on-message", Vdebug_on_message,
 37669                doc: /* If non-nil, debug if a message matching this regexp is displayed.  */);
 37670   Vdebug_on_message = Qnil;
 37671 
 37672   DEFVAR_LISP ("set-message-function", Vset_message_function,
 37673                doc: /* If non-nil, function to handle display of echo-area messages.
 37674 The function is called with one argument that is the text of a message.
 37675 If this function returns nil, the message is displayed in the echo area
 37676 as usual.  If the function returns a string, the returned string is
 37677 displayed in the echo area.  If this function returns any other non-nil
 37678 value, this means that the message was already handled, and the original
 37679 message text will not be displayed in the echo area.
 37680 
 37681 Also see `clear-message-function' (which can be used to clear the
 37682 message displayed by this function), and `command-error-function'
 37683 (which controls how error messages are displayed).  */);
 37684   Vset_message_function = Qnil;
 37685 
 37686   DEFSYM (Qdont_clear_message, "dont-clear-message");
 37687   DEFVAR_LISP ("clear-message-function", Vclear_message_function,
 37688                doc: /* If non-nil, function to clear echo-area messages.
 37689 Usually this function is called when the next input event arrives.
 37690 It is expected to clear the message displayed by its counterpart
 37691 function specified by `set-message-function'.
 37692 
 37693 The function is called without arguments.
 37694 
 37695 If this function returns a value that isn't `dont-clear-message', the
 37696 message is cleared from the echo area as usual.  If this function
 37697 returns `dont-clear-message', this means that the message was already
 37698 handled, and the original message text will not be cleared from the
 37699 echo area.  */);
 37700   Vclear_message_function = Qnil;
 37701 
 37702   DEFVAR_LISP ("redisplay--all-windows-cause", Vredisplay__all_windows_cause,
 37703                doc: /* Code of the cause for redisplaying all windows.
 37704 Internal use only.  */);
 37705   Vredisplay__all_windows_cause = Fmake_hash_table (0, NULL);
 37706 
 37707   DEFVAR_LISP ("redisplay--mode-lines-cause", Vredisplay__mode_lines_cause,
 37708                doc: /* Code of the cause for redisplaying mode lines.
 37709 Internal use only.  */);
 37710   Vredisplay__mode_lines_cause = Fmake_hash_table (0, NULL);
 37711 
 37712   DEFVAR_BOOL ("redisplay--inhibit-bidi", redisplay__inhibit_bidi,
 37713      doc: /* Non-nil means it is not safe to attempt bidi reordering for display.  */);
 37714   /* Initialize to t, since we need to disable reordering until
 37715      loadup.el successfully loads charprop.el.  */
 37716   redisplay__inhibit_bidi = true;
 37717 
 37718   DEFVAR_BOOL ("display-raw-bytes-as-hex", display_raw_bytes_as_hex,
 37719     doc: /* Non-nil means display raw bytes in hexadecimal format.
 37720 The default is to use octal format (\\200) whereas hexadecimal (\\x80)
 37721 may be more familiar to users.  */);
 37722   display_raw_bytes_as_hex = false;
 37723 
 37724   DEFVAR_BOOL ("mouse-fine-grained-tracking", mouse_fine_grained_tracking,
 37725     doc: /* Non-nil for pixel-wise mouse-movement.
 37726 When nil, mouse-movement events will not be generated as long as the
 37727 mouse stays within the extent of a single glyph (except for images).  */);
 37728   mouse_fine_grained_tracking = false;
 37729 
 37730   DEFVAR_BOOL ("tab-bar--dragging-in-progress", tab_bar__dragging_in_progress,
 37731     doc: /* Non-nil when maybe dragging tab bar item.  */);
 37732   tab_bar__dragging_in_progress = false;
 37733 
 37734   DEFVAR_BOOL ("redisplay-skip-initial-frame", redisplay_skip_initial_frame,
 37735     doc: /* Non-nil means skip redisplay of the initial frame.
 37736 The initial frame is the text-mode frame used by Emacs internally during
 37737 the early stages of startup.  That frame is not displayed anywhere, so
 37738 skipping it is best except in special circumstances such as running
 37739 redisplay tests in batch mode.   */);
 37740   redisplay_skip_initial_frame = true;
 37741 
 37742   DEFVAR_BOOL ("redisplay-skip-fontification-on-input",
 37743                redisplay_skip_fontification_on_input,
 37744     doc: /* Skip `fontification_functions` when there is input pending.
 37745 If non-nil and there was input pending at the beginning of the command,
 37746 the `fontification_functions` hook is not run.  This usually does not
 37747 affect the display because redisplay is completely skipped anyway if input
 37748 was pending, but it can make scrolling smoother by avoiding
 37749 unnecessary fontification.
 37750 It is similar to `fast-but-imprecise-scrolling' with similar tradeoffs,
 37751 but with the advantage that it should only affect the behavior when Emacs
 37752 has trouble keeping up with the incoming input rate.  */);
 37753   redisplay_skip_fontification_on_input = false;
 37754 
 37755   DEFVAR_BOOL ("redisplay-adhoc-scroll-in-resize-mini-windows",
 37756                redisplay_adhoc_scroll_in_resize_mini_windows,
 37757     doc: /* If nil always use normal scrolling in minibuffer windows.
 37758 Otherwise, use custom-tailored code after resizing minibuffer windows to try
 37759 and display the most important part of the minibuffer.   */);
 37760   /* See bug#43519 for some discussion around this.  */
 37761   redisplay_adhoc_scroll_in_resize_mini_windows = true;
 37762 
 37763   DEFVAR_BOOL ("composition-break-at-point", composition_break_at_point,
 37764     doc: /* If non-nil, prevent auto-composition of characters around point.
 37765 This makes it easier to edit character sequences that are
 37766 composed on display.  */);
 37767   composition_break_at_point = false;
 37768 
 37769   DEFVAR_INT ("max-redisplay-ticks", max_redisplay_ticks,
 37770     doc: /* Maximum number of redisplay ticks before aborting redisplay of a window.
 37771 
 37772 This allows to abort the display of a window if the amount of low-level
 37773 redisplay operations exceeds the value of this variable.  When display of
 37774 a window is aborted due to this reason, the buffer shown in that window
 37775 will not have its windows redisplayed until the buffer is modified or until
 37776 you type \\[recenter-top-bottom] with one of its windows selected.
 37777 You can also decide to kill the buffer and visit it in some
 37778 other way, like under `so-long-mode' or literally.
 37779 
 37780 The default value is zero, which disables this feature.
 37781 The recommended non-zero value is between 100000 and 1000000,
 37782 depending on your patience and the speed of your system.  */);
 37783   max_redisplay_ticks = 0;
 37784 }
 37785 
 37786 
 37787 /* Initialize this module when Emacs starts.  */
 37788 
 37789 void
 37790 init_xdisp (void)
 37791 {
 37792   CHARPOS (this_line_start_pos) = 0;
 37793 
 37794   echo_area_window = minibuf_window;
 37795 
 37796   if (!noninteractive)
 37797     {
 37798       struct window *m = XWINDOW (minibuf_window);
 37799       Lisp_Object frame = m->frame;
 37800       struct frame *f = XFRAME (frame);
 37801       Lisp_Object root = FRAME_ROOT_WINDOW (f);
 37802       struct window *r = XWINDOW (root);
 37803       int i;
 37804 
 37805       r->top_line = FRAME_TOP_MARGIN (f);
 37806       r->pixel_top = r->top_line * FRAME_LINE_HEIGHT (f);
 37807       r->total_cols = FRAME_COLS (f);
 37808       r->pixel_width = r->total_cols * FRAME_COLUMN_WIDTH (f);
 37809       r->total_lines = FRAME_TOTAL_LINES (f) - 1 - FRAME_MARGINS (f);
 37810       r->pixel_height = r->total_lines * FRAME_LINE_HEIGHT (f);
 37811 
 37812       m->top_line = FRAME_TOTAL_LINES (f) - 1;
 37813       m->pixel_top = m->top_line * FRAME_LINE_HEIGHT (f);
 37814       m->total_cols = FRAME_COLS (f);
 37815       m->pixel_width = m->total_cols * FRAME_COLUMN_WIDTH (f);
 37816       m->total_lines = 1;
 37817       m->pixel_height = m->total_lines * FRAME_LINE_HEIGHT (f);
 37818 
 37819       scratch_glyph_row.glyphs[TEXT_AREA] = scratch_glyphs;
 37820       scratch_glyph_row.glyphs[TEXT_AREA + 1]
 37821         = scratch_glyphs + MAX_SCRATCH_GLYPHS;
 37822 
 37823       /* The default ellipsis glyphs `...'.  */
 37824       for (i = 0; i < 3; ++i)
 37825         default_invis_vector[i] = make_fixnum ('.');
 37826     }
 37827 
 37828   {
 37829     /* Allocate the buffer for frame titles.
 37830        Also used for `format-mode-line'.  */
 37831     int size = 100;
 37832     mode_line_noprop_buf = xmalloc (size);
 37833     mode_line_noprop_buf_end = mode_line_noprop_buf + size;
 37834     mode_line_noprop_ptr = mode_line_noprop_buf;
 37835     mode_line_target = MODE_LINE_DISPLAY;
 37836   }
 37837 
 37838   help_echo_showing_p = false;
 37839 }
 37840 
 37841 #ifdef HAVE_WINDOW_SYSTEM
 37842 
 37843 /* Platform-independent portion of hourglass implementation.  */
 37844 
 37845 /* Timer function of hourglass_atimer.  */
 37846 
 37847 static void
 37848 show_hourglass (struct atimer *timer)
 37849 {
 37850   /* The timer implementation will cancel this timer automatically
 37851      after this function has run.  Set hourglass_atimer to null
 37852      so that we know the timer doesn't have to be canceled.  */
 37853   hourglass_atimer = NULL;
 37854 
 37855   if (!hourglass_shown_p)
 37856     {
 37857       Lisp_Object tail, frame;
 37858 
 37859       block_input ();
 37860 
 37861       FOR_EACH_FRAME (tail, frame)
 37862         {
 37863           struct frame *f = XFRAME (frame);
 37864 
 37865           if (FRAME_LIVE_P (f) && FRAME_WINDOW_P (f)
 37866               && FRAME_RIF (f)->show_hourglass)
 37867             FRAME_RIF (f)->show_hourglass (f);
 37868         }
 37869 
 37870       hourglass_shown_p = true;
 37871       unblock_input ();
 37872     }
 37873 }
 37874 
 37875 /* Cancel a currently active hourglass timer, and start a new one.  */
 37876 
 37877 void
 37878 start_hourglass (void)
 37879 {
 37880   struct timespec delay;
 37881 
 37882   cancel_hourglass ();
 37883 
 37884   if (FIXNUMP (Vhourglass_delay)
 37885       && XFIXNUM (Vhourglass_delay) > 0)
 37886     delay = make_timespec (min (XFIXNUM (Vhourglass_delay),
 37887                                   TYPE_MAXIMUM (time_t)),
 37888                            0);
 37889   else if (FLOATP (Vhourglass_delay)
 37890            && XFLOAT_DATA (Vhourglass_delay) > 0)
 37891     delay = dtotimespec (XFLOAT_DATA (Vhourglass_delay));
 37892   else
 37893     delay = make_timespec (DEFAULT_HOURGLASS_DELAY, 0);
 37894 
 37895   hourglass_atimer = start_atimer (ATIMER_RELATIVE, delay,
 37896                                    show_hourglass, NULL);
 37897 }
 37898 
 37899 /* Cancel the hourglass cursor timer if active, hide a busy cursor if
 37900    shown.  */
 37901 
 37902 void
 37903 cancel_hourglass (void)
 37904 {
 37905   if (hourglass_atimer)
 37906     {
 37907       cancel_atimer (hourglass_atimer);
 37908       hourglass_atimer = NULL;
 37909     }
 37910 
 37911   if (hourglass_shown_p)
 37912     {
 37913       Lisp_Object tail, frame;
 37914 
 37915       block_input ();
 37916 
 37917       FOR_EACH_FRAME (tail, frame)
 37918         {
 37919           struct frame *f = XFRAME (frame);
 37920 
 37921           if (FRAME_LIVE_P (f) && FRAME_WINDOW_P (f)
 37922               && FRAME_RIF (f)->hide_hourglass)
 37923             FRAME_RIF (f)->hide_hourglass (f);
 37924 #ifdef HAVE_NTGUI
 37925           /* No cursors on non GUI frames - restore to stock arrow cursor.  */
 37926           else if (!FRAME_W32_P (f))
 37927             w32_arrow_cursor ();
 37928 #endif
 37929         }
 37930 
 37931       hourglass_shown_p = false;
 37932       unblock_input ();
 37933     }
 37934 }
 37935 
 37936 /* Return a correction to be applied to G->pixel_width when it is
 37937    displayed in MOUSE_FACE.  This is needed for the first and the last
 37938    glyphs of text inside a face with :box when it is displayed with
 37939    MOUSE_FACE that has a different or no :box attribute.
 37940    ORIGINAL_FACE is the face G was originally drawn in, and MOUSE_FACE
 37941    is the face it will be drawn in now.  ROW is the G's glyph row and
 37942    W is its window.  */
 37943 static int
 37944 adjust_glyph_width_for_mouse_face (struct glyph *g, struct glyph_row *row,
 37945                                    struct window *w,
 37946                                    struct face *original_face,
 37947                                    struct face *mouse_face)
 37948 {
 37949   int sum = 0;
 37950 
 37951   bool do_left_box_p = g->left_box_line_p;
 37952   bool do_right_box_p = g->right_box_line_p;
 37953 
 37954   /* This is required because we test some parameters of the image
 37955      slice before applying the box in produce_image_glyph.  */
 37956   if (g->type == IMAGE_GLYPH)
 37957     {
 37958       if (!row->reversed_p)
 37959         {
 37960           struct image *img = IMAGE_FROM_ID (WINDOW_XFRAME (w),
 37961                                              g->u.img_id);
 37962           do_left_box_p = g->left_box_line_p &&
 37963             g->slice.img.x == 0;
 37964           do_right_box_p = g->right_box_line_p &&
 37965             g->slice.img.x + g->slice.img.width == img->width;
 37966         }
 37967       else
 37968         {
 37969           struct image *img = IMAGE_FROM_ID (WINDOW_XFRAME (w),
 37970                                              g->u.img_id);
 37971           do_left_box_p = g->left_box_line_p &&
 37972             g->slice.img.x + g->slice.img.width == img->width;
 37973           do_right_box_p = g->right_box_line_p &&
 37974             g->slice.img.x == 0;
 37975         }
 37976     }
 37977 
 37978   /* If the glyph has a left box line, subtract it from the offset.  */
 37979   if (do_left_box_p)
 37980     sum -= max (0, original_face->box_vertical_line_width);
 37981   /* Likewise with the right box line, as there may be a
 37982      box there as well.  */
 37983   if (do_right_box_p)
 37984     sum -= max (0, original_face->box_vertical_line_width);
 37985   /* Now add the line widths from the new face.  */
 37986   if (g->left_box_line_p)
 37987     sum += max (0, mouse_face->box_vertical_line_width);
 37988   if (g->right_box_line_p)
 37989     sum += max (0, mouse_face->box_vertical_line_width);
 37990 
 37991   return sum;
 37992 }
 37993 
 37994 /* Get the offset due to mouse-highlight to apply before drawing
 37995    phys_cursor, and return it in OFFSET.  ROW should be the row that
 37996    is under mouse face and contains the phys cursor.
 37997 
 37998    This is required because the produce_XXX_glyph series of functions
 37999    add the width of the various vertical box lines to the total width
 38000    of the glyphs, but that must be updated when the row is put under
 38001    mouse face, which can have different box dimensions.  */
 38002 static void
 38003 get_cursor_offset_for_mouse_face (struct window *w, struct glyph_row *row,
 38004                                   int *offset)
 38005 {
 38006   int sum = 0;
 38007   /* Return because the mode line can't possibly have a cursor. */
 38008   if (row->mode_line_p)
 38009     return;
 38010 
 38011   block_input ();
 38012 
 38013   struct frame *f = WINDOW_XFRAME (w);
 38014   Mouse_HLInfo *hlinfo = MOUSE_HL_INFO (f);
 38015   struct glyph *start, *end;
 38016   struct face *mouse_face = FACE_FROM_ID (f, hlinfo->mouse_face_face_id);
 38017   int hpos = w->phys_cursor.hpos;
 38018   end = &row->glyphs[TEXT_AREA][hpos];
 38019 
 38020   if (!row->reversed_p)
 38021     {
 38022       if (MATRIX_ROW_VPOS (row, w->current_matrix) ==
 38023           hlinfo->mouse_face_beg_row)
 38024         start = &row->glyphs[TEXT_AREA][hlinfo->mouse_face_beg_col];
 38025       else
 38026         start = row->glyphs[TEXT_AREA];
 38027     }
 38028   else
 38029     {
 38030       if (MATRIX_ROW_VPOS (row, w->current_matrix) ==
 38031           hlinfo->mouse_face_end_row)
 38032         start = &row->glyphs[TEXT_AREA][hlinfo->mouse_face_end_col];
 38033       else
 38034         start = &row->glyphs[TEXT_AREA][row->used[TEXT_AREA] - 1];
 38035     }
 38036 
 38037   /* Calculate the offset by which to correct phys_cursor x if we are
 38038      drawing the cursor inside mouse-face highlighted text.  */
 38039 
 38040   for ( ; row->reversed_p ? start > end : start < end;
 38041           row->reversed_p ? --start : ++start)
 38042     sum += adjust_glyph_width_for_mouse_face (start, row, w,
 38043                                               FACE_FROM_ID (f, start->face_id),
 38044                                               mouse_face);
 38045 
 38046   if (row->reversed_p)
 38047     sum = -sum;
 38048 
 38049   *offset = sum;
 38050 
 38051   unblock_input ();
 38052 }
 38053 #endif /* HAVE_WINDOW_SYSTEM */

/* [<][>][^][v][top][bottom][index][help] */